(RE_STRING_CHAR): New macro.
[emacs.git] / src / regex.c
blob711f7c7afa9fe847b52e5f6f3442795db00c143d
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P10003.2/D11.2, except for
3 internationalization features.)
5 Copyright (C) 1993,94,95,96,97,98,2000 Free Software Foundation, Inc.
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.
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.
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. */
22 /* TODO:
23 - detect nasty infinite loops like "\\(\\)+?ab" when matching "ac".
24 - use `keep_string' more often than just .*\n.
25 - structure the opcode space into opcode+flag.
26 - merge with glic's regex.[ch]
28 That's it for now -sm */
30 /* AIX requires this to be the first thing in the file. */
31 #if defined (_AIX) && !defined (REGEX_MALLOC)
32 #pragma alloca
33 #endif
35 #undef _GNU_SOURCE
36 #define _GNU_SOURCE
38 #ifdef emacs
39 /* Converts the pointer to the char to BEG-based offset from the start. */
40 #define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
41 #define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
42 #else
43 #define PTR_TO_OFFSET(d) 0
44 #endif
46 #ifdef HAVE_CONFIG_H
47 #include <config.h>
48 #endif
50 /* We need this for `regex.h', and perhaps for the Emacs include files. */
51 #include <sys/types.h>
53 /* This is for other GNU distributions with internationalized messages. */
54 #if HAVE_LIBINTL_H || defined (_LIBC)
55 # include <libintl.h>
56 #else
57 # define gettext(msgid) (msgid)
58 #endif
60 #ifndef gettext_noop
61 /* This define is so xgettext can find the internationalizable
62 strings. */
63 #define gettext_noop(String) String
64 #endif
66 /* The `emacs' switch turns on certain matching commands
67 that make sense only in Emacs. */
68 #ifdef emacs
70 #include "lisp.h"
71 #include "buffer.h"
73 /* Make syntax table lookup grant data in gl_state. */
74 #define SYNTAX_ENTRY_VIA_PROPERTY
76 #include "syntax.h"
77 #include "charset.h"
78 #include "category.h"
80 #define malloc xmalloc
81 #define realloc xrealloc
82 #define free xfree
84 #define RE_STRING_CHAR(p, s) \
85 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
87 #else /* not emacs */
89 /* If we are not linking with Emacs proper,
90 we can't use the relocating allocator
91 even if config.h says that we can. */
92 #undef REL_ALLOC
94 #if defined (STDC_HEADERS) || defined (_LIBC)
95 #include <stdlib.h>
96 #else
97 char *malloc ();
98 char *realloc ();
99 #endif
101 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
102 If nothing else has been done, use the method below. */
103 #ifdef INHIBIT_STRING_HEADER
104 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
105 #if !defined (bzero) && !defined (bcopy)
106 #undef INHIBIT_STRING_HEADER
107 #endif
108 #endif
109 #endif
111 /* This is the normal way of making sure we have a bcopy and a bzero.
112 This is used in most programs--a few other programs avoid this
113 by defining INHIBIT_STRING_HEADER. */
114 #ifndef INHIBIT_STRING_HEADER
115 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
116 #include <string.h>
117 #ifndef bcmp
118 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
119 #endif
120 #ifndef bcopy
121 #define bcopy(s, d, n) memcpy ((d), (s), (n))
122 #endif
123 #ifndef bzero
124 #define bzero(s, n) memset ((s), 0, (n))
125 #endif
126 #else
127 #include <strings.h>
128 #endif
129 #endif
131 /* Define the syntax stuff for \<, \>, etc. */
133 /* This must be nonzero for the wordchar and notwordchar pattern
134 commands in re_match_2. */
135 #ifndef Sword
136 #define Sword 1
137 #endif
139 #ifdef SWITCH_ENUM_BUG
140 #define SWITCH_ENUM_CAST(x) ((int)(x))
141 #else
142 #define SWITCH_ENUM_CAST(x) (x)
143 #endif
145 #ifdef SYNTAX_TABLE
147 extern char *re_syntax_table;
149 #else /* not SYNTAX_TABLE */
151 /* How many characters in the character set. */
152 #define CHAR_SET_SIZE 256
154 static char re_syntax_table[CHAR_SET_SIZE];
156 static void
157 init_syntax_once ()
159 register int c;
160 static int done = 0;
162 if (done)
163 return;
165 bzero (re_syntax_table, sizeof re_syntax_table);
167 for (c = 'a'; c <= 'z'; c++)
168 re_syntax_table[c] = Sword;
170 for (c = 'A'; c <= 'Z'; c++)
171 re_syntax_table[c] = Sword;
173 for (c = '0'; c <= '9'; c++)
174 re_syntax_table[c] = Sword;
176 re_syntax_table['_'] = Sword;
178 done = 1;
181 #endif /* not SYNTAX_TABLE */
183 #define SYNTAX(c) re_syntax_table[c]
185 /* Dummy macros for non-Emacs environments. */
186 #define BASE_LEADING_CODE_P(c) (0)
187 #define WORD_BOUNDARY_P(c1, c2) (0)
188 #define CHAR_HEAD_P(p) (1)
189 #define SINGLE_BYTE_CHAR_P(c) (1)
190 #define SAME_CHARSET_P(c1, c2) (1)
191 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
192 #define STRING_CHAR(p, s) (*(p))
193 #define RE_STRING_CHAR STRING_CHAR
194 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
195 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
196 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
197 #endif /* not emacs */
199 #ifndef RE_TRANSLATE
200 #define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
201 #define RE_TRANSLATE_P(TBL) (TBL)
202 #endif
204 /* Get the interface, including the syntax bits. */
205 #include "regex.h"
207 /* isalpha etc. are used for the character classes. */
208 #include <ctype.h>
210 #ifdef emacs
212 /* 1 if C is an ASCII character. */
213 #define IS_REAL_ASCII(c) ((c) < 0200)
215 /* 1 if C is a unibyte character. */
216 #define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
218 /* The Emacs definitions should not be directly affected by locales. */
220 /* In Emacs, these are only used for single-byte characters. */
221 #define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
222 #define ISCNTRL(c) ((c) < ' ')
223 #define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
224 || ((c) >= 'a' && (c) <= 'f') \
225 || ((c) >= 'A' && (c) <= 'F'))
227 /* This is only used for single-byte characters. */
228 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
230 /* The rest must handle multibyte characters. */
232 #define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
233 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
234 : 1)
236 #define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
237 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
238 : 1)
240 #define ISALNUM(c) (IS_REAL_ASCII (c) \
241 ? (((c) >= 'a' && (c) <= 'z') \
242 || ((c) >= 'A' && (c) <= 'Z') \
243 || ((c) >= '0' && (c) <= '9')) \
244 : SYNTAX (c) == Sword)
246 #define ISALPHA(c) (IS_REAL_ASCII (c) \
247 ? (((c) >= 'a' && (c) <= 'z') \
248 || ((c) >= 'A' && (c) <= 'Z')) \
249 : SYNTAX (c) == Sword)
251 #define ISLOWER(c) (LOWERCASEP (c))
253 #define ISPUNCT(c) (IS_REAL_ASCII (c) \
254 ? ((c) > ' ' && (c) < 0177 \
255 && !(((c) >= 'a' && (c) <= 'z') \
256 || ((c) >= 'A' && (c) <= 'Z') \
257 || ((c) >= '0' && (c) <= '9'))) \
258 : SYNTAX (c) != Sword)
260 #define ISSPACE(c) (SYNTAX (c) == Swhitespace)
262 #define ISUPPER(c) (UPPERCASEP (c))
264 #define ISWORD(c) (SYNTAX (c) == Sword)
266 #else /* not emacs */
268 /* Jim Meyering writes:
270 "... Some ctype macros are valid only for character codes that
271 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
272 using /bin/cc or gcc but without giving an ansi option). So, all
273 ctype uses should be through macros like ISPRINT... If
274 STDC_HEADERS is defined, then autoconf has verified that the ctype
275 macros don't need to be guarded with references to isascii. ...
276 Defining isascii to 1 should let any compiler worth its salt
277 eliminate the && through constant folding." */
279 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
280 #define ISASCII(c) 1
281 #else
282 #define ISASCII(c) isascii(c)
283 #endif
285 /* 1 if C is an ASCII character. */
286 #define IS_REAL_ASCII(c) ((c) < 0200)
288 /* This distinction is not meaningful, except in Emacs. */
289 #define ISUNIBYTE(c) 1
291 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
292 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
293 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
295 #ifdef isblank
296 #define ISBLANK(c) (ISASCII (c) && isblank (c))
297 #else
298 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
299 #endif
300 #ifdef isgraph
301 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
302 #else
303 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
304 #endif
306 #define ISPRINT(c) (ISASCII (c) && isprint (c))
307 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
308 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
309 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
310 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
311 #define ISLOWER(c) (ISASCII (c) && islower (c))
312 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
313 #define ISSPACE(c) (ISASCII (c) && isspace (c))
314 #define ISUPPER(c) (ISASCII (c) && isupper (c))
315 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
317 #define ISWORD(c) ISALPHA(c)
319 #endif /* not emacs */
321 #ifndef NULL
322 #define NULL (void *)0
323 #endif
325 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
326 since ours (we hope) works properly with all combinations of
327 machines, compilers, `char' and `unsigned char' argument types.
328 (Per Bothner suggested the basic approach.) */
329 #undef SIGN_EXTEND_CHAR
330 #if __STDC__
331 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
332 #else /* not __STDC__ */
333 /* As in Harbison and Steele. */
334 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
335 #endif
337 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
338 use `alloca' instead of `malloc'. This is because using malloc in
339 re_search* or re_match* could cause memory leaks when C-g is used in
340 Emacs; also, malloc is slower and causes storage fragmentation. On
341 the other hand, malloc is more portable, and easier to debug.
343 Because we sometimes use alloca, some routines have to be macros,
344 not functions -- `alloca'-allocated space disappears at the end of the
345 function it is called in. */
347 #ifdef REGEX_MALLOC
349 #define REGEX_ALLOCATE malloc
350 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
351 #define REGEX_FREE free
353 #else /* not REGEX_MALLOC */
355 /* Emacs already defines alloca, sometimes. */
356 #ifndef alloca
358 /* Make alloca work the best possible way. */
359 #ifdef __GNUC__
360 #define alloca __builtin_alloca
361 #else /* not __GNUC__ */
362 #if HAVE_ALLOCA_H
363 #include <alloca.h>
364 #else /* not __GNUC__ or HAVE_ALLOCA_H */
365 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
366 #ifndef _AIX /* Already did AIX, up at the top. */
367 char *alloca ();
368 #endif /* not _AIX */
369 #endif
370 #endif /* not HAVE_ALLOCA_H */
371 #endif /* not __GNUC__ */
373 #endif /* not alloca */
375 #define REGEX_ALLOCATE alloca
377 /* Assumes a `char *destination' variable. */
378 #define REGEX_REALLOCATE(source, osize, nsize) \
379 (destination = (char *) alloca (nsize), \
380 bcopy (source, destination, osize), \
381 destination)
383 /* No need to do anything to free, after alloca. */
384 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
386 #endif /* not REGEX_MALLOC */
388 /* Define how to allocate the failure stack. */
390 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
392 #define REGEX_ALLOCATE_STACK(size) \
393 r_alloc (&failure_stack_ptr, (size))
394 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
395 r_re_alloc (&failure_stack_ptr, (nsize))
396 #define REGEX_FREE_STACK(ptr) \
397 r_alloc_free (&failure_stack_ptr)
399 #else /* not using relocating allocator */
401 #ifdef REGEX_MALLOC
403 #define REGEX_ALLOCATE_STACK malloc
404 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
405 #define REGEX_FREE_STACK free
407 #else /* not REGEX_MALLOC */
409 #define REGEX_ALLOCATE_STACK alloca
411 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
412 REGEX_REALLOCATE (source, osize, nsize)
413 /* No need to explicitly free anything. */
414 #define REGEX_FREE_STACK(arg)
416 #endif /* not REGEX_MALLOC */
417 #endif /* not using relocating allocator */
420 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
421 `string1' or just past its end. This works if PTR is NULL, which is
422 a good thing. */
423 #define FIRST_STRING_P(ptr) \
424 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
426 /* (Re)Allocate N items of type T using malloc, or fail. */
427 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
428 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
429 #define RETALLOC_IF(addr, n, t) \
430 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
431 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
433 #define BYTEWIDTH 8 /* In bits. */
435 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
437 #undef MAX
438 #undef MIN
439 #define MAX(a, b) ((a) > (b) ? (a) : (b))
440 #define MIN(a, b) ((a) < (b) ? (a) : (b))
442 /* Type of source-pattern and string chars. */
443 typedef const unsigned char re_char;
445 typedef char boolean;
446 #define false 0
447 #define true 1
449 static int re_match_2_internal ();
451 /* These are the command codes that appear in compiled regular
452 expressions. Some opcodes are followed by argument bytes. A
453 command code can specify any interpretation whatsoever for its
454 arguments. Zero bytes may appear in the compiled regular expression. */
456 typedef enum
458 no_op = 0,
460 /* Succeed right away--no more backtracking. */
461 succeed,
463 /* Followed by one byte giving n, then by n literal bytes. */
464 exactn,
466 /* Matches any (more or less) character. */
467 anychar,
469 /* Matches any one char belonging to specified set. First
470 following byte is number of bitmap bytes. Then come bytes
471 for a bitmap saying which chars are in. Bits in each byte
472 are ordered low-bit-first. A character is in the set if its
473 bit is 1. A character too large to have a bit in the map is
474 automatically not in the set.
476 If the length byte has the 0x80 bit set, then that stuff
477 is followed by a range table:
478 2 bytes of flags for character sets (low 8 bits, high 8 bits)
479 See RANGE_TABLE_WORK_BITS below.
480 2 bytes, the number of pairs that follow
481 pairs, each 2 multibyte characters,
482 each multibyte character represented as 3 bytes. */
483 charset,
485 /* Same parameters as charset, but match any character that is
486 not one of those specified. */
487 charset_not,
489 /* Start remembering the text that is matched, for storing in a
490 register. Followed by one byte with the register number, in
491 the range 0 to one less than the pattern buffer's re_nsub
492 field. */
493 start_memory,
495 /* Stop remembering the text that is matched and store it in a
496 memory register. Followed by one byte with the register
497 number, in the range 0 to one less than `re_nsub' in the
498 pattern buffer. */
499 stop_memory,
501 /* Match a duplicate of something remembered. Followed by one
502 byte containing the register number. */
503 duplicate,
505 /* Fail unless at beginning of line. */
506 begline,
508 /* Fail unless at end of line. */
509 endline,
511 /* Succeeds if at beginning of buffer (if emacs) or at beginning
512 of string to be matched (if not). */
513 begbuf,
515 /* Analogously, for end of buffer/string. */
516 endbuf,
518 /* Followed by two byte relative address to which to jump. */
519 jump,
521 /* Followed by two-byte relative address of place to resume at
522 in case of failure. */
523 on_failure_jump,
525 /* Like on_failure_jump, but pushes a placeholder instead of the
526 current string position when executed. */
527 on_failure_keep_string_jump,
529 /* Just like `on_failure_jump', except that it checks that we
530 don't get stuck in an infinite loop (matching an empty string
531 indefinitely). */
532 on_failure_jump_loop,
534 /* A smart `on_failure_jump' used for greedy * and + operators.
535 It analyses the loop before which it is put and if the
536 loop does not require backtracking, it changes itself to
537 `on_failure_keep_string_jump' and short-circuits the loop,
538 else it just defaults to changing itself into `on_failure_jump'.
539 It assumes that it is pointing to just past a `jump'. */
540 on_failure_jump_smart,
542 /* Followed by two-byte relative address and two-byte number n.
543 After matching N times, jump to the address upon failure. */
544 succeed_n,
546 /* Followed by two-byte relative address, and two-byte number n.
547 Jump to the address N times, then fail. */
548 jump_n,
550 /* Set the following two-byte relative address to the
551 subsequent two-byte number. The address *includes* the two
552 bytes of number. */
553 set_number_at,
555 wordchar, /* Matches any word-constituent character. */
556 notwordchar, /* Matches any char that is not a word-constituent. */
558 wordbeg, /* Succeeds if at word beginning. */
559 wordend, /* Succeeds if at word end. */
561 wordbound, /* Succeeds if at a word boundary. */
562 notwordbound /* Succeeds if not at a word boundary. */
564 #ifdef emacs
565 ,before_dot, /* Succeeds if before point. */
566 at_dot, /* Succeeds if at point. */
567 after_dot, /* Succeeds if after point. */
569 /* Matches any character whose syntax is specified. Followed by
570 a byte which contains a syntax code, e.g., Sword. */
571 syntaxspec,
573 /* Matches any character whose syntax is not that specified. */
574 notsyntaxspec,
576 /* Matches any character whose category-set contains the specified
577 category. The operator is followed by a byte which contains a
578 category code (mnemonic ASCII character). */
579 categoryspec,
581 /* Matches any character whose category-set does not contain the
582 specified category. The operator is followed by a byte which
583 contains the category code (mnemonic ASCII character). */
584 notcategoryspec
585 #endif /* emacs */
586 } re_opcode_t;
588 /* Common operations on the compiled pattern. */
590 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
592 #define STORE_NUMBER(destination, number) \
593 do { \
594 (destination)[0] = (number) & 0377; \
595 (destination)[1] = (number) >> 8; \
596 } while (0)
598 /* Same as STORE_NUMBER, except increment DESTINATION to
599 the byte after where the number is stored. Therefore, DESTINATION
600 must be an lvalue. */
602 #define STORE_NUMBER_AND_INCR(destination, number) \
603 do { \
604 STORE_NUMBER (destination, number); \
605 (destination) += 2; \
606 } while (0)
608 /* Put into DESTINATION a number stored in two contiguous bytes starting
609 at SOURCE. */
611 #define EXTRACT_NUMBER(destination, source) \
612 do { \
613 (destination) = *(source) & 0377; \
614 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
615 } while (0)
617 #ifdef DEBUG
618 static void
619 extract_number (dest, source)
620 int *dest;
621 unsigned char *source;
623 int temp = SIGN_EXTEND_CHAR (*(source + 1));
624 *dest = *source & 0377;
625 *dest += temp << 8;
628 #ifndef EXTRACT_MACROS /* To debug the macros. */
629 #undef EXTRACT_NUMBER
630 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
631 #endif /* not EXTRACT_MACROS */
633 #endif /* DEBUG */
635 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
636 SOURCE must be an lvalue. */
638 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
639 do { \
640 EXTRACT_NUMBER (destination, source); \
641 (source) += 2; \
642 } while (0)
644 #ifdef DEBUG
645 static void
646 extract_number_and_incr (destination, source)
647 int *destination;
648 unsigned char **source;
650 extract_number (destination, *source);
651 *source += 2;
654 #ifndef EXTRACT_MACROS
655 #undef EXTRACT_NUMBER_AND_INCR
656 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
657 extract_number_and_incr (&dest, &src)
658 #endif /* not EXTRACT_MACROS */
660 #endif /* DEBUG */
662 /* Store a multibyte character in three contiguous bytes starting
663 DESTINATION, and increment DESTINATION to the byte after where the
664 character is stored. Therefore, DESTINATION must be an lvalue. */
666 #define STORE_CHARACTER_AND_INCR(destination, character) \
667 do { \
668 (destination)[0] = (character) & 0377; \
669 (destination)[1] = ((character) >> 8) & 0377; \
670 (destination)[2] = (character) >> 16; \
671 (destination) += 3; \
672 } while (0)
674 /* Put into DESTINATION a character stored in three contiguous bytes
675 starting at SOURCE. */
677 #define EXTRACT_CHARACTER(destination, source) \
678 do { \
679 (destination) = ((source)[0] \
680 | ((source)[1] << 8) \
681 | ((source)[2] << 16)); \
682 } while (0)
685 /* Macros for charset. */
687 /* Size of bitmap of charset P in bytes. P is a start of charset,
688 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
689 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
691 /* Nonzero if charset P has range table. */
692 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
694 /* Return the address of range table of charset P. But not the start
695 of table itself, but the before where the number of ranges is
696 stored. `2 +' means to skip re_opcode_t and size of bitmap,
697 and the 2 bytes of flags at the start of the range table. */
698 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
700 /* Extract the bit flags that start a range table. */
701 #define CHARSET_RANGE_TABLE_BITS(p) \
702 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
703 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
705 /* Test if C is listed in the bitmap of charset P. */
706 #define CHARSET_LOOKUP_BITMAP(p, c) \
707 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
708 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
710 /* Return the address of end of RANGE_TABLE. COUNT is number of
711 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
712 is start of range and end of range. `* 3' is size of each start
713 and end. */
714 #define CHARSET_RANGE_TABLE_END(range_table, count) \
715 ((range_table) + (count) * 2 * 3)
717 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
718 COUNT is number of ranges in RANGE_TABLE. */
719 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
720 do \
722 int range_start, range_end; \
723 unsigned char *p; \
724 unsigned char *range_table_end \
725 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
727 for (p = (range_table); p < range_table_end; p += 2 * 3) \
729 EXTRACT_CHARACTER (range_start, p); \
730 EXTRACT_CHARACTER (range_end, p + 3); \
732 if (range_start <= (c) && (c) <= range_end) \
734 (not) = !(not); \
735 break; \
739 while (0)
741 /* Test if C is in range table of CHARSET. The flag NOT is negated if
742 C is listed in it. */
743 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
744 do \
746 /* Number of ranges in range table. */ \
747 int count; \
748 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
750 EXTRACT_NUMBER_AND_INCR (count, range_table); \
751 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
753 while (0)
755 /* If DEBUG is defined, Regex prints many voluminous messages about what
756 it is doing (if the variable `debug' is nonzero). If linked with the
757 main program in `iregex.c', you can enter patterns and strings
758 interactively. And if linked with the main program in `main.c' and
759 the other test files, you can run the already-written tests. */
761 #ifdef DEBUG
763 /* We use standard I/O for debugging. */
764 #include <stdio.h>
766 /* It is useful to test things that ``must'' be true when debugging. */
767 #include <assert.h>
769 static int debug = -100000;
771 #define DEBUG_STATEMENT(e) e
772 #define DEBUG_PRINT1(x) if (debug > 0) printf (x)
773 #define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
774 #define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
775 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
776 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
777 if (debug > 0) print_partial_compiled_pattern (s, e)
778 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
779 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
782 /* Print the fastmap in human-readable form. */
784 void
785 print_fastmap (fastmap)
786 char *fastmap;
788 unsigned was_a_range = 0;
789 unsigned i = 0;
791 while (i < (1 << BYTEWIDTH))
793 if (fastmap[i++])
795 was_a_range = 0;
796 putchar (i - 1);
797 while (i < (1 << BYTEWIDTH) && fastmap[i])
799 was_a_range = 1;
800 i++;
802 if (was_a_range)
804 printf ("-");
805 putchar (i - 1);
809 putchar ('\n');
813 /* Print a compiled pattern string in human-readable form, starting at
814 the START pointer into it and ending just before the pointer END. */
816 void
817 print_partial_compiled_pattern (start, end)
818 unsigned char *start;
819 unsigned char *end;
821 int mcnt, mcnt2;
822 unsigned char *p = start;
823 unsigned char *pend = end;
825 if (start == NULL)
827 printf ("(null)\n");
828 return;
831 /* Loop over pattern commands. */
832 while (p < pend)
834 printf ("%d:\t", p - start);
836 switch ((re_opcode_t) *p++)
838 case no_op:
839 printf ("/no_op");
840 break;
842 case succeed:
843 printf ("/succeed");
844 break;
846 case exactn:
847 mcnt = *p++;
848 printf ("/exactn/%d", mcnt);
851 putchar ('/');
852 putchar (*p++);
854 while (--mcnt);
855 break;
857 case start_memory:
858 printf ("/start_memory/%d", *p++);
859 break;
861 case stop_memory:
862 printf ("/stop_memory/%d", *p++);
863 break;
865 case duplicate:
866 printf ("/duplicate/%d", *p++);
867 break;
869 case anychar:
870 printf ("/anychar");
871 break;
873 case charset:
874 case charset_not:
876 register int c, last = -100;
877 register int in_range = 0;
878 int length = CHARSET_BITMAP_SIZE (p - 1);
879 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
881 printf ("/charset [%s",
882 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
884 assert (p + *p < pend);
886 for (c = 0; c < 256; c++)
887 if (c / 8 < length
888 && (p[1 + (c/8)] & (1 << (c % 8))))
890 /* Are we starting a range? */
891 if (last + 1 == c && ! in_range)
893 putchar ('-');
894 in_range = 1;
896 /* Have we broken a range? */
897 else if (last + 1 != c && in_range)
899 putchar (last);
900 in_range = 0;
903 if (! in_range)
904 putchar (c);
906 last = c;
909 if (in_range)
910 putchar (last);
912 putchar (']');
914 p += 1 + length;
916 if (has_range_table)
918 int count;
919 printf ("has-range-table");
921 /* ??? Should print the range table; for now, just skip it. */
922 p += 2; /* skip range table bits */
923 EXTRACT_NUMBER_AND_INCR (count, p);
924 p = CHARSET_RANGE_TABLE_END (p, count);
927 break;
929 case begline:
930 printf ("/begline");
931 break;
933 case endline:
934 printf ("/endline");
935 break;
937 case on_failure_jump:
938 extract_number_and_incr (&mcnt, &p);
939 printf ("/on_failure_jump to %d", p + mcnt - start);
940 break;
942 case on_failure_keep_string_jump:
943 extract_number_and_incr (&mcnt, &p);
944 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
945 break;
947 case on_failure_jump_loop:
948 extract_number_and_incr (&mcnt, &p);
949 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
950 break;
952 case on_failure_jump_smart:
953 extract_number_and_incr (&mcnt, &p);
954 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
955 break;
957 case jump:
958 extract_number_and_incr (&mcnt, &p);
959 printf ("/jump to %d", p + mcnt - start);
960 break;
962 case succeed_n:
963 extract_number_and_incr (&mcnt, &p);
964 extract_number_and_incr (&mcnt2, &p);
965 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
966 break;
968 case jump_n:
969 extract_number_and_incr (&mcnt, &p);
970 extract_number_and_incr (&mcnt2, &p);
971 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
972 break;
974 case set_number_at:
975 extract_number_and_incr (&mcnt, &p);
976 extract_number_and_incr (&mcnt2, &p);
977 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
978 break;
980 case wordbound:
981 printf ("/wordbound");
982 break;
984 case notwordbound:
985 printf ("/notwordbound");
986 break;
988 case wordbeg:
989 printf ("/wordbeg");
990 break;
992 case wordend:
993 printf ("/wordend");
995 #ifdef emacs
996 case before_dot:
997 printf ("/before_dot");
998 break;
1000 case at_dot:
1001 printf ("/at_dot");
1002 break;
1004 case after_dot:
1005 printf ("/after_dot");
1006 break;
1008 case syntaxspec:
1009 printf ("/syntaxspec");
1010 mcnt = *p++;
1011 printf ("/%d", mcnt);
1012 break;
1014 case notsyntaxspec:
1015 printf ("/notsyntaxspec");
1016 mcnt = *p++;
1017 printf ("/%d", mcnt);
1018 break;
1019 #endif /* emacs */
1021 case wordchar:
1022 printf ("/wordchar");
1023 break;
1025 case notwordchar:
1026 printf ("/notwordchar");
1027 break;
1029 case begbuf:
1030 printf ("/begbuf");
1031 break;
1033 case endbuf:
1034 printf ("/endbuf");
1035 break;
1037 default:
1038 printf ("?%d", *(p-1));
1041 putchar ('\n');
1044 printf ("%d:\tend of pattern.\n", p - start);
1048 void
1049 print_compiled_pattern (bufp)
1050 struct re_pattern_buffer *bufp;
1052 unsigned char *buffer = bufp->buffer;
1054 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1055 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used, bufp->allocated);
1057 if (bufp->fastmap_accurate && bufp->fastmap)
1059 printf ("fastmap: ");
1060 print_fastmap (bufp->fastmap);
1063 printf ("re_nsub: %d\t", bufp->re_nsub);
1064 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1065 printf ("can_be_null: %d\t", bufp->can_be_null);
1066 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1067 printf ("no_sub: %d\t", bufp->no_sub);
1068 printf ("not_bol: %d\t", bufp->not_bol);
1069 printf ("not_eol: %d\t", bufp->not_eol);
1070 printf ("syntax: %d\n", bufp->syntax);
1071 fflush (stdout);
1072 /* Perhaps we should print the translate table? */
1076 void
1077 print_double_string (where, string1, size1, string2, size2)
1078 re_char *where;
1079 re_char *string1;
1080 re_char *string2;
1081 int size1;
1082 int size2;
1084 unsigned this_char;
1086 if (where == NULL)
1087 printf ("(null)");
1088 else
1090 if (FIRST_STRING_P (where))
1092 for (this_char = where - string1; this_char < size1; this_char++)
1093 putchar (string1[this_char]);
1095 where = string2;
1098 for (this_char = where - string2; this_char < size2; this_char++)
1099 putchar (string2[this_char]);
1103 #else /* not DEBUG */
1105 #undef assert
1106 #define assert(e)
1108 #define DEBUG_STATEMENT(e)
1109 #define DEBUG_PRINT1(x)
1110 #define DEBUG_PRINT2(x1, x2)
1111 #define DEBUG_PRINT3(x1, x2, x3)
1112 #define DEBUG_PRINT4(x1, x2, x3, x4)
1113 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1114 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1116 #endif /* not DEBUG */
1118 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1119 also be assigned to arbitrarily: each pattern buffer stores its own
1120 syntax, so it can be changed between regex compilations. */
1121 /* This has no initializer because initialized variables in Emacs
1122 become read-only after dumping. */
1123 reg_syntax_t re_syntax_options;
1126 /* Specify the precise syntax of regexps for compilation. This provides
1127 for compatibility for various utilities which historically have
1128 different, incompatible syntaxes.
1130 The argument SYNTAX is a bit mask comprised of the various bits
1131 defined in regex.h. We return the old syntax. */
1133 reg_syntax_t
1134 re_set_syntax (syntax)
1135 reg_syntax_t syntax;
1137 reg_syntax_t ret = re_syntax_options;
1139 re_syntax_options = syntax;
1140 return ret;
1143 /* This table gives an error message for each of the error codes listed
1144 in regex.h. Obviously the order here has to be same as there.
1145 POSIX doesn't require that we do anything for REG_NOERROR,
1146 but why not be nice? */
1148 static const char *re_error_msgid[] =
1150 gettext_noop ("Success"), /* REG_NOERROR */
1151 gettext_noop ("No match"), /* REG_NOMATCH */
1152 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1153 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1154 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1155 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1156 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1157 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1158 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1159 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1160 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1161 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1162 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1163 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1164 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1165 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1166 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1169 /* Avoiding alloca during matching, to placate r_alloc. */
1171 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1172 searching and matching functions should not call alloca. On some
1173 systems, alloca is implemented in terms of malloc, and if we're
1174 using the relocating allocator routines, then malloc could cause a
1175 relocation, which might (if the strings being searched are in the
1176 ralloc heap) shift the data out from underneath the regexp
1177 routines.
1179 Here's another reason to avoid allocation: Emacs
1180 processes input from X in a signal handler; processing X input may
1181 call malloc; if input arrives while a matching routine is calling
1182 malloc, then we're scrod. But Emacs can't just block input while
1183 calling matching routines; then we don't notice interrupts when
1184 they come in. So, Emacs blocks input around all regexp calls
1185 except the matching calls, which it leaves unprotected, in the
1186 faith that they will not malloc. */
1188 /* Normally, this is fine. */
1189 #define MATCH_MAY_ALLOCATE
1191 /* When using GNU C, we are not REALLY using the C alloca, no matter
1192 what config.h may say. So don't take precautions for it. */
1193 #ifdef __GNUC__
1194 #undef C_ALLOCA
1195 #endif
1197 /* The match routines may not allocate if (1) they would do it with malloc
1198 and (2) it's not safe for them to use malloc.
1199 Note that if REL_ALLOC is defined, matching would not use malloc for the
1200 failure stack, but we would still use it for the register vectors;
1201 so REL_ALLOC should not affect this. */
1202 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1203 #undef MATCH_MAY_ALLOCATE
1204 #endif
1207 /* Failure stack declarations and macros; both re_compile_fastmap and
1208 re_match_2 use a failure stack. These have to be macros because of
1209 REGEX_ALLOCATE_STACK. */
1212 /* Approximate number of failure points for which to initially allocate space
1213 when matching. If this number is exceeded, we allocate more
1214 space, so it is not a hard limit. */
1215 #ifndef INIT_FAILURE_ALLOC
1216 #define INIT_FAILURE_ALLOC 20
1217 #endif
1219 /* Roughly the maximum number of failure points on the stack. Would be
1220 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1221 This is a variable only so users of regex can assign to it; we never
1222 change it ourselves. */
1223 #if defined (MATCH_MAY_ALLOCATE)
1224 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1225 whose default stack limit is 2mb. In order for a larger
1226 value to work reliably, you have to try to make it accord
1227 with the process stack limit. */
1228 int re_max_failures = 40000;
1229 #else
1230 int re_max_failures = 4000;
1231 #endif
1233 union fail_stack_elt
1235 const unsigned char *pointer;
1236 unsigned int integer;
1239 typedef union fail_stack_elt fail_stack_elt_t;
1241 typedef struct
1243 fail_stack_elt_t *stack;
1244 unsigned size;
1245 unsigned avail; /* Offset of next open position. */
1246 unsigned frame; /* Offset of the cur constructed frame. */
1247 } fail_stack_type;
1249 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1250 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1251 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1254 /* Define macros to initialize and free the failure stack.
1255 Do `return -2' if the alloc fails. */
1257 #ifdef MATCH_MAY_ALLOCATE
1258 #define INIT_FAIL_STACK() \
1259 do { \
1260 fail_stack.stack = (fail_stack_elt_t *) \
1261 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1262 * sizeof (fail_stack_elt_t)); \
1264 if (fail_stack.stack == NULL) \
1265 return -2; \
1267 fail_stack.size = INIT_FAILURE_ALLOC; \
1268 fail_stack.avail = 0; \
1269 fail_stack.frame = 0; \
1270 } while (0)
1272 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1273 #else
1274 #define INIT_FAIL_STACK() \
1275 do { \
1276 fail_stack.avail = 0; \
1277 fail_stack.frame = 0; \
1278 } while (0)
1280 #define RESET_FAIL_STACK()
1281 #endif
1284 /* Double the size of FAIL_STACK, up to a limit
1285 which allows approximately `re_max_failures' items.
1287 Return 1 if succeeds, and 0 if either ran out of memory
1288 allocating space for it or it was already too large.
1290 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1292 /* Factor to increase the failure stack size by
1293 when we increase it.
1294 This used to be 2, but 2 was too wasteful
1295 because the old discarded stacks added up to as much space
1296 were as ultimate, maximum-size stack. */
1297 #define FAIL_STACK_GROWTH_FACTOR 4
1299 #define GROW_FAIL_STACK(fail_stack) \
1300 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1301 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1302 ? 0 \
1303 : ((fail_stack).stack \
1304 = (fail_stack_elt_t *) \
1305 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1306 (fail_stack).size * sizeof (fail_stack_elt_t), \
1307 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1308 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1309 * FAIL_STACK_GROWTH_FACTOR))), \
1311 (fail_stack).stack == NULL \
1312 ? 0 \
1313 : ((fail_stack).size \
1314 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1315 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1316 * FAIL_STACK_GROWTH_FACTOR)) \
1317 / sizeof (fail_stack_elt_t)), \
1318 1)))
1321 /* Push pointer POINTER on FAIL_STACK.
1322 Return 1 if was able to do so and 0 if ran out of memory allocating
1323 space to do so. */
1324 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1325 ((FAIL_STACK_FULL () \
1326 && !GROW_FAIL_STACK (FAIL_STACK)) \
1327 ? 0 \
1328 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1330 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1332 /* Push a pointer value onto the failure stack.
1333 Assumes the variable `fail_stack'. Probably should only
1334 be called from within `PUSH_FAILURE_POINT'. */
1335 #define PUSH_FAILURE_POINTER(item) \
1336 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1338 /* This pushes an integer-valued item onto the failure stack.
1339 Assumes the variable `fail_stack'. Probably should only
1340 be called from within `PUSH_FAILURE_POINT'. */
1341 #define PUSH_FAILURE_INT(item) \
1342 fail_stack.stack[fail_stack.avail++].integer = (item)
1344 /* Push a fail_stack_elt_t value onto the failure stack.
1345 Assumes the variable `fail_stack'. Probably should only
1346 be called from within `PUSH_FAILURE_POINT'. */
1347 #define PUSH_FAILURE_ELT(item) \
1348 fail_stack.stack[fail_stack.avail++] = (item)
1350 /* These three POP... operations complement the three PUSH... operations.
1351 All assume that `fail_stack' is nonempty. */
1352 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1353 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1354 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1356 /* Individual items aside from the registers. */
1357 #define NUM_NONREG_ITEMS 3
1359 /* Used to examine the stack (to detect infinite loops). */
1360 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1361 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1362 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1363 #define TOP_FAILURE_HANDLE() fail_stack.frame
1366 #define ENSURE_FAIL_STACK(space) \
1367 while (REMAINING_AVAIL_SLOTS <= space) { \
1368 if (!GROW_FAIL_STACK (fail_stack)) \
1369 return -2; \
1370 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1371 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1374 /* Push register NUM onto the stack. */
1375 #define PUSH_FAILURE_REG(num) \
1376 do { \
1377 char *destination; \
1378 ENSURE_FAIL_STACK(3); \
1379 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1380 num, regstart[num], regend[num]); \
1381 PUSH_FAILURE_POINTER (regstart[num]); \
1382 PUSH_FAILURE_POINTER (regend[num]); \
1383 PUSH_FAILURE_INT (num); \
1384 } while (0)
1386 /* Pop a saved register off the stack. */
1387 #define POP_FAILURE_REG() \
1388 do { \
1389 int reg = POP_FAILURE_INT (); \
1390 regend[reg] = POP_FAILURE_POINTER (); \
1391 regstart[reg] = POP_FAILURE_POINTER (); \
1392 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1393 reg, regstart[reg], regend[reg]); \
1394 } while (0)
1396 /* Check that we are not stuck in an infinite loop. */
1397 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1398 do { \
1399 int failure = TOP_FAILURE_HANDLE(); \
1400 /* Check for infinite matching loops */ \
1401 while (failure > 0 && \
1402 (FAILURE_STR (failure) == string_place \
1403 || FAILURE_STR (failure) == NULL)) \
1405 assert (FAILURE_PAT (failure) >= bufp->buffer \
1406 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1407 if (FAILURE_PAT (failure) == pat_cur) \
1408 goto fail; \
1409 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1410 failure = NEXT_FAILURE_HANDLE(failure); \
1412 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1413 } while (0)
1415 /* Push the information about the state we will need
1416 if we ever fail back to it.
1418 Requires variables fail_stack, regstart, regend and
1419 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1420 declared.
1422 Does `return FAILURE_CODE' if runs out of memory. */
1424 #define PUSH_FAILURE_POINT(pattern, string_place) \
1425 do { \
1426 char *destination; \
1427 /* Must be int, so when we don't save any registers, the arithmetic \
1428 of 0 + -1 isn't done as unsigned. */ \
1430 DEBUG_STATEMENT (failure_id++); \
1431 DEBUG_STATEMENT (nfailure_points_pushed++); \
1432 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1433 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1434 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1436 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1438 DEBUG_PRINT1 ("\n"); \
1440 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1441 PUSH_FAILURE_INT (fail_stack.frame); \
1443 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1444 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1445 DEBUG_PRINT1 ("'\n"); \
1446 PUSH_FAILURE_POINTER (string_place); \
1448 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1449 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1450 PUSH_FAILURE_POINTER (pattern); \
1452 /* Close the frame by moving the frame pointer past it. */ \
1453 fail_stack.frame = fail_stack.avail; \
1454 } while (0)
1456 /* Estimate the size of data pushed by a typical failure stack entry.
1457 An estimate is all we need, because all we use this for
1458 is to choose a limit for how big to make the failure stack. */
1460 #define TYPICAL_FAILURE_SIZE 20
1462 /* How many items can still be added to the stack without overflowing it. */
1463 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1466 /* Pops what PUSH_FAIL_STACK pushes.
1468 We restore into the parameters, all of which should be lvalues:
1469 STR -- the saved data position.
1470 PAT -- the saved pattern position.
1471 REGSTART, REGEND -- arrays of string positions.
1473 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1474 `pend', `string1', `size1', `string2', and `size2'. */
1476 #define POP_FAILURE_POINT(str, pat) \
1477 do { \
1478 assert (!FAIL_STACK_EMPTY ()); \
1480 /* Remove failure points and point to how many regs pushed. */ \
1481 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1482 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1483 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1485 /* Pop the saved registers. */ \
1486 while (fail_stack.frame < fail_stack.avail) \
1487 POP_FAILURE_REG (); \
1489 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1490 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1491 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1493 /* If the saved string location is NULL, it came from an \
1494 on_failure_keep_string_jump opcode, and we want to throw away the \
1495 saved NULL, thus retaining our current position in the string. */ \
1496 str = (re_char *) POP_FAILURE_POINTER (); \
1497 DEBUG_PRINT2 (" Popping string %p: `", str); \
1498 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1499 DEBUG_PRINT1 ("'\n"); \
1501 fail_stack.frame = POP_FAILURE_INT (); \
1502 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1504 assert (fail_stack.avail >= 0); \
1505 assert (fail_stack.frame <= fail_stack.avail); \
1507 DEBUG_STATEMENT (nfailure_points_popped++); \
1508 } while (0) /* POP_FAILURE_POINT */
1512 /* Registers are set to a sentinel when they haven't yet matched. */
1513 #define REG_UNSET_VALUE NULL
1514 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1516 /* Subroutine declarations and macros for regex_compile. */
1518 static void store_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc, int arg));
1519 static void store_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1520 int arg1, int arg2));
1521 static void insert_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1522 int arg, unsigned char *end));
1523 static void insert_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1524 int arg1, int arg2, unsigned char *end));
1525 static boolean at_begline_loc_p _RE_ARGS((const unsigned char *pattern,
1526 const unsigned char *p,
1527 reg_syntax_t syntax));
1528 static boolean at_endline_loc_p _RE_ARGS((const unsigned char *p,
1529 const unsigned char *pend,
1530 reg_syntax_t syntax));
1531 static unsigned char *skip_one_char _RE_ARGS((unsigned char *p));
1533 /* Fetch the next character in the uncompiled pattern---translating it
1534 if necessary. Also cast from a signed character in the constant
1535 string passed to us by the user to an unsigned char that we can use
1536 as an array index (in, e.g., `translate'). */
1537 #ifndef PATFETCH
1538 #define PATFETCH(c) \
1539 do { \
1540 PATFETCH_RAW (c); \
1541 if (RE_TRANSLATE_P (translate)) c = RE_TRANSLATE (translate, c); \
1542 } while (0)
1543 #endif
1545 /* Fetch the next character in the uncompiled pattern, with no
1546 translation. */
1547 #define PATFETCH_RAW(c) \
1548 do {if (p == pend) return REG_EEND; \
1549 c = *p++; \
1550 } while (0)
1552 /* Go backwards one character in the pattern. */
1553 #define PATUNFETCH p--
1556 /* If `translate' is non-null, return translate[D], else just D. We
1557 cast the subscript to translate because some data is declared as
1558 `char *', to avoid warnings when a string constant is passed. But
1559 when we use a character as a subscript we must make it unsigned. */
1560 #ifndef TRANSLATE
1561 #define TRANSLATE(d) \
1562 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1563 #endif
1566 /* Macros for outputting the compiled pattern into `buffer'. */
1568 /* If the buffer isn't allocated when it comes in, use this. */
1569 #define INIT_BUF_SIZE 32
1571 /* Make sure we have at least N more bytes of space in buffer. */
1572 #define GET_BUFFER_SPACE(n) \
1573 while (b - bufp->buffer + (n) > bufp->allocated) \
1574 EXTEND_BUFFER ()
1576 /* Make sure we have one more byte of buffer space and then add C to it. */
1577 #define BUF_PUSH(c) \
1578 do { \
1579 GET_BUFFER_SPACE (1); \
1580 *b++ = (unsigned char) (c); \
1581 } while (0)
1584 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1585 #define BUF_PUSH_2(c1, c2) \
1586 do { \
1587 GET_BUFFER_SPACE (2); \
1588 *b++ = (unsigned char) (c1); \
1589 *b++ = (unsigned char) (c2); \
1590 } while (0)
1593 /* As with BUF_PUSH_2, except for three bytes. */
1594 #define BUF_PUSH_3(c1, c2, c3) \
1595 do { \
1596 GET_BUFFER_SPACE (3); \
1597 *b++ = (unsigned char) (c1); \
1598 *b++ = (unsigned char) (c2); \
1599 *b++ = (unsigned char) (c3); \
1600 } while (0)
1603 /* Store a jump with opcode OP at LOC to location TO. We store a
1604 relative address offset by the three bytes the jump itself occupies. */
1605 #define STORE_JUMP(op, loc, to) \
1606 store_op1 (op, loc, (to) - (loc) - 3)
1608 /* Likewise, for a two-argument jump. */
1609 #define STORE_JUMP2(op, loc, to, arg) \
1610 store_op2 (op, loc, (to) - (loc) - 3, arg)
1612 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1613 #define INSERT_JUMP(op, loc, to) \
1614 insert_op1 (op, loc, (to) - (loc) - 3, b)
1616 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1617 #define INSERT_JUMP2(op, loc, to, arg) \
1618 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1621 /* This is not an arbitrary limit: the arguments which represent offsets
1622 into the pattern are two bytes long. So if 2^16 bytes turns out to
1623 be too small, many things would have to change. */
1624 #define MAX_BUF_SIZE (1L << 16)
1627 /* Extend the buffer by twice its current size via realloc and
1628 reset the pointers that pointed into the old block to point to the
1629 correct places in the new one. If extending the buffer results in it
1630 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1631 #define EXTEND_BUFFER() \
1632 do { \
1633 unsigned char *old_buffer = bufp->buffer; \
1634 if (bufp->allocated == MAX_BUF_SIZE) \
1635 return REG_ESIZE; \
1636 bufp->allocated <<= 1; \
1637 if (bufp->allocated > MAX_BUF_SIZE) \
1638 bufp->allocated = MAX_BUF_SIZE; \
1639 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1640 if (bufp->buffer == NULL) \
1641 return REG_ESPACE; \
1642 /* If the buffer moved, move all the pointers into it. */ \
1643 if (old_buffer != bufp->buffer) \
1645 b = (b - old_buffer) + bufp->buffer; \
1646 begalt = (begalt - old_buffer) + bufp->buffer; \
1647 if (fixup_alt_jump) \
1648 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1649 if (laststart) \
1650 laststart = (laststart - old_buffer) + bufp->buffer; \
1651 if (pending_exact) \
1652 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1654 } while (0)
1657 /* Since we have one byte reserved for the register number argument to
1658 {start,stop}_memory, the maximum number of groups we can report
1659 things about is what fits in that byte. */
1660 #define MAX_REGNUM 255
1662 /* But patterns can have more than `MAX_REGNUM' registers. We just
1663 ignore the excess. */
1664 typedef unsigned regnum_t;
1667 /* Macros for the compile stack. */
1669 /* Since offsets can go either forwards or backwards, this type needs to
1670 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1671 typedef int pattern_offset_t;
1673 typedef struct
1675 pattern_offset_t begalt_offset;
1676 pattern_offset_t fixup_alt_jump;
1677 pattern_offset_t laststart_offset;
1678 regnum_t regnum;
1679 } compile_stack_elt_t;
1682 typedef struct
1684 compile_stack_elt_t *stack;
1685 unsigned size;
1686 unsigned avail; /* Offset of next open position. */
1687 } compile_stack_type;
1690 #define INIT_COMPILE_STACK_SIZE 32
1692 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1693 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1695 /* The next available element. */
1696 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1699 /* Structure to manage work area for range table. */
1700 struct range_table_work_area
1702 int *table; /* actual work area. */
1703 int allocated; /* allocated size for work area in bytes. */
1704 int used; /* actually used size in words. */
1705 int bits; /* flag to record character classes */
1708 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1709 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1710 do { \
1711 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1713 (work_area).allocated += 16 * sizeof (int); \
1714 if ((work_area).table) \
1715 (work_area).table \
1716 = (int *) realloc ((work_area).table, (work_area).allocated); \
1717 else \
1718 (work_area).table \
1719 = (int *) malloc ((work_area).allocated); \
1720 if ((work_area).table == 0) \
1721 FREE_STACK_RETURN (REG_ESPACE); \
1723 } while (0)
1725 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1726 (work_area).bits |= (bit)
1728 /* These bits represent the various character classes such as [:alnum:]
1729 in a charset's range table. */
1730 #define BIT_ALNUM 0x1
1731 #define BIT_ALPHA 0x2
1732 #define BIT_WORD 0x4
1733 #define BIT_ASCII 0x8
1734 #define BIT_NONASCII 0x10
1735 #define BIT_GRAPH 0x20
1736 #define BIT_LOWER 0x40
1737 #define BIT_PRINT 0x80
1738 #define BIT_PUNCT 0x100
1739 #define BIT_SPACE 0x200
1740 #define BIT_UPPER 0x400
1741 #define BIT_UNIBYTE 0x800
1742 #define BIT_MULTIBYTE 0x1000
1744 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1745 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1746 do { \
1747 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1748 (work_area).table[(work_area).used++] = (range_start); \
1749 (work_area).table[(work_area).used++] = (range_end); \
1750 } while (0)
1752 /* Free allocated memory for WORK_AREA. */
1753 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1754 do { \
1755 if ((work_area).table) \
1756 free ((work_area).table); \
1757 } while (0)
1759 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1760 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1761 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1762 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1765 /* Set the bit for character C in a list. */
1766 #define SET_LIST_BIT(c) \
1767 (b[((unsigned char) (c)) / BYTEWIDTH] \
1768 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1771 /* Get the next unsigned number in the uncompiled pattern. */
1772 #define GET_UNSIGNED_NUMBER(num) \
1773 do { if (p != pend) \
1775 PATFETCH (c); \
1776 while (ISDIGIT (c)) \
1778 if (num < 0) \
1779 num = 0; \
1780 num = num * 10 + c - '0'; \
1781 if (p == pend) \
1782 break; \
1783 PATFETCH (c); \
1786 } while (0)
1788 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1790 #define IS_CHAR_CLASS(string) \
1791 (STREQ (string, "alpha") || STREQ (string, "upper") \
1792 || STREQ (string, "lower") || STREQ (string, "digit") \
1793 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1794 || STREQ (string, "space") || STREQ (string, "print") \
1795 || STREQ (string, "punct") || STREQ (string, "graph") \
1796 || STREQ (string, "cntrl") || STREQ (string, "blank") \
1797 || STREQ (string, "word") \
1798 || STREQ (string, "ascii") || STREQ (string, "nonascii") \
1799 || STREQ (string, "unibyte") || STREQ (string, "multibyte"))
1801 /* QUIT is only used on NTemacs. */
1802 #if !defined (WINDOWSNT) || !defined (emacs)
1803 #undef QUIT
1804 #define QUIT
1805 #endif
1807 #ifndef MATCH_MAY_ALLOCATE
1809 /* If we cannot allocate large objects within re_match_2_internal,
1810 we make the fail stack and register vectors global.
1811 The fail stack, we grow to the maximum size when a regexp
1812 is compiled.
1813 The register vectors, we adjust in size each time we
1814 compile a regexp, according to the number of registers it needs. */
1816 static fail_stack_type fail_stack;
1818 /* Size with which the following vectors are currently allocated.
1819 That is so we can make them bigger as needed,
1820 but never make them smaller. */
1821 static int regs_allocated_size;
1823 static re_char ** regstart, ** regend;
1824 static re_char **best_regstart, **best_regend;
1826 /* Make the register vectors big enough for NUM_REGS registers,
1827 but don't make them smaller. */
1829 static
1830 regex_grow_registers (num_regs)
1831 int num_regs;
1833 if (num_regs > regs_allocated_size)
1835 RETALLOC_IF (regstart, num_regs, re_char *);
1836 RETALLOC_IF (regend, num_regs, re_char *);
1837 RETALLOC_IF (best_regstart, num_regs, re_char *);
1838 RETALLOC_IF (best_regend, num_regs, re_char *);
1840 regs_allocated_size = num_regs;
1844 #endif /* not MATCH_MAY_ALLOCATE */
1846 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
1847 compile_stack,
1848 regnum_t regnum));
1850 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1851 Returns one of error codes defined in `regex.h', or zero for success.
1853 Assumes the `allocated' (and perhaps `buffer') and `translate'
1854 fields are set in BUFP on entry.
1856 If it succeeds, results are put in BUFP (if it returns an error, the
1857 contents of BUFP are undefined):
1858 `buffer' is the compiled pattern;
1859 `syntax' is set to SYNTAX;
1860 `used' is set to the length of the compiled pattern;
1861 `fastmap_accurate' is zero;
1862 `re_nsub' is the number of subexpressions in PATTERN;
1863 `not_bol' and `not_eol' are zero;
1865 The `fastmap' and `newline_anchor' fields are neither
1866 examined nor set. */
1868 /* Insert the `jump' from the end of last alternative to "here".
1869 The space for the jump has already been allocated. */
1870 #define FIXUP_ALT_JUMP() \
1871 do { \
1872 if (fixup_alt_jump) \
1873 STORE_JUMP (jump, fixup_alt_jump, b); \
1874 } while (0)
1877 /* Return, freeing storage we allocated. */
1878 #define FREE_STACK_RETURN(value) \
1879 do { \
1880 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1881 free (compile_stack.stack); \
1882 return value; \
1883 } while (0)
1885 static reg_errcode_t
1886 regex_compile (pattern, size, syntax, bufp)
1887 re_char *pattern;
1888 int size;
1889 reg_syntax_t syntax;
1890 struct re_pattern_buffer *bufp;
1892 /* We fetch characters from PATTERN here. Even though PATTERN is
1893 `char *' (i.e., signed), we declare these variables as unsigned, so
1894 they can be reliably used as array indices. */
1895 register unsigned int c, c1;
1897 /* A random temporary spot in PATTERN. */
1898 re_char *p1;
1900 /* Points to the end of the buffer, where we should append. */
1901 register unsigned char *b;
1903 /* Keeps track of unclosed groups. */
1904 compile_stack_type compile_stack;
1906 /* Points to the current (ending) position in the pattern. */
1907 #ifdef AIX
1908 /* `const' makes AIX compiler fail. */
1909 unsigned char *p = pattern;
1910 #else
1911 re_char *p = pattern;
1912 #endif
1913 re_char *pend = pattern + size;
1915 /* How to translate the characters in the pattern. */
1916 RE_TRANSLATE_TYPE translate = bufp->translate;
1918 /* Address of the count-byte of the most recently inserted `exactn'
1919 command. This makes it possible to tell if a new exact-match
1920 character can be added to that command or if the character requires
1921 a new `exactn' command. */
1922 unsigned char *pending_exact = 0;
1924 /* Address of start of the most recently finished expression.
1925 This tells, e.g., postfix * where to find the start of its
1926 operand. Reset at the beginning of groups and alternatives. */
1927 unsigned char *laststart = 0;
1929 /* Address of beginning of regexp, or inside of last group. */
1930 unsigned char *begalt;
1932 /* Place in the uncompiled pattern (i.e., the {) to
1933 which to go back if the interval is invalid. */
1934 re_char *beg_interval;
1936 /* Address of the place where a forward jump should go to the end of
1937 the containing expression. Each alternative of an `or' -- except the
1938 last -- ends with a forward jump of this sort. */
1939 unsigned char *fixup_alt_jump = 0;
1941 /* Counts open-groups as they are encountered. Remembered for the
1942 matching close-group on the compile stack, so the same register
1943 number is put in the stop_memory as the start_memory. */
1944 regnum_t regnum = 0;
1946 /* Work area for range table of charset. */
1947 struct range_table_work_area range_table_work;
1949 #ifdef DEBUG
1950 debug++;
1951 DEBUG_PRINT1 ("\nCompiling pattern: ");
1952 if (debug > 0)
1954 unsigned debug_count;
1956 for (debug_count = 0; debug_count < size; debug_count++)
1957 putchar (pattern[debug_count]);
1958 putchar ('\n');
1960 #endif /* DEBUG */
1962 /* Initialize the compile stack. */
1963 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1964 if (compile_stack.stack == NULL)
1965 return REG_ESPACE;
1967 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1968 compile_stack.avail = 0;
1970 range_table_work.table = 0;
1971 range_table_work.allocated = 0;
1973 /* Initialize the pattern buffer. */
1974 bufp->syntax = syntax;
1975 bufp->fastmap_accurate = 0;
1976 bufp->not_bol = bufp->not_eol = 0;
1978 /* Set `used' to zero, so that if we return an error, the pattern
1979 printer (for debugging) will think there's no pattern. We reset it
1980 at the end. */
1981 bufp->used = 0;
1983 /* Always count groups, whether or not bufp->no_sub is set. */
1984 bufp->re_nsub = 0;
1986 #ifdef emacs
1987 /* bufp->multibyte is set before regex_compile is called, so don't alter
1988 it. */
1989 #else /* not emacs */
1990 /* Nothing is recognized as a multibyte character. */
1991 bufp->multibyte = 0;
1992 #endif
1994 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1995 /* Initialize the syntax table. */
1996 init_syntax_once ();
1997 #endif
1999 if (bufp->allocated == 0)
2001 if (bufp->buffer)
2002 { /* If zero allocated, but buffer is non-null, try to realloc
2003 enough space. This loses if buffer's address is bogus, but
2004 that is the user's responsibility. */
2005 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2007 else
2008 { /* Caller did not allocate a buffer. Do it for them. */
2009 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2011 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2013 bufp->allocated = INIT_BUF_SIZE;
2016 begalt = b = bufp->buffer;
2018 /* Loop through the uncompiled pattern until we're at the end. */
2019 while (p != pend)
2021 PATFETCH (c);
2023 switch (c)
2025 case '^':
2027 if ( /* If at start of pattern, it's an operator. */
2028 p == pattern + 1
2029 /* If context independent, it's an operator. */
2030 || syntax & RE_CONTEXT_INDEP_ANCHORS
2031 /* Otherwise, depends on what's come before. */
2032 || at_begline_loc_p (pattern, p, syntax))
2033 BUF_PUSH (begline);
2034 else
2035 goto normal_char;
2037 break;
2040 case '$':
2042 if ( /* If at end of pattern, it's an operator. */
2043 p == pend
2044 /* If context independent, it's an operator. */
2045 || syntax & RE_CONTEXT_INDEP_ANCHORS
2046 /* Otherwise, depends on what's next. */
2047 || at_endline_loc_p (p, pend, syntax))
2048 BUF_PUSH (endline);
2049 else
2050 goto normal_char;
2052 break;
2055 case '+':
2056 case '?':
2057 if ((syntax & RE_BK_PLUS_QM)
2058 || (syntax & RE_LIMITED_OPS))
2059 goto normal_char;
2060 handle_plus:
2061 case '*':
2062 /* If there is no previous pattern... */
2063 if (!laststart)
2065 if (syntax & RE_CONTEXT_INVALID_OPS)
2066 FREE_STACK_RETURN (REG_BADRPT);
2067 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2068 goto normal_char;
2072 /* 1 means zero (many) matches is allowed. */
2073 boolean zero_times_ok = 0, many_times_ok = 0;
2074 boolean greedy = 1;
2076 /* If there is a sequence of repetition chars, collapse it
2077 down to just one (the right one). We can't combine
2078 interval operators with these because of, e.g., `a{2}*',
2079 which should only match an even number of `a's. */
2081 for (;;)
2083 if (!(syntax & RE_ALL_GREEDY)
2084 && c == '?' && (zero_times_ok || many_times_ok))
2085 greedy = 0;
2086 else
2088 zero_times_ok |= c != '+';
2089 many_times_ok |= c != '?';
2092 if (p == pend)
2093 break;
2095 PATFETCH (c);
2097 if (c == '*'
2098 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2101 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2103 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2105 PATFETCH (c1);
2106 if (!(c1 == '+' || c1 == '?'))
2108 PATUNFETCH;
2109 PATUNFETCH;
2110 break;
2113 c = c1;
2115 else
2117 PATUNFETCH;
2118 break;
2121 /* If we get here, we found another repeat character. */
2124 /* Star, etc. applied to an empty pattern is equivalent
2125 to an empty pattern. */
2126 if (!laststart || laststart == b)
2127 break;
2129 /* Now we know whether or not zero matches is allowed
2130 and also whether or not two or more matches is allowed. */
2131 if (greedy)
2133 if (many_times_ok)
2135 boolean simple = skip_one_char (laststart) == b;
2136 unsigned int startoffset = 0;
2137 assert (skip_one_char (laststart) <= b);
2139 if (!zero_times_ok && simple)
2140 { /* Since simple * loops can be made faster by using
2141 on_failure_keep_string_jump, we turn simple P+
2142 into PP* if P is simple. */
2143 unsigned char *p1, *p2;
2144 startoffset = b - laststart;
2145 GET_BUFFER_SPACE (startoffset);
2146 p1 = b; p2 = laststart;
2147 while (p2 < p1)
2148 *b++ = *p2++;
2149 zero_times_ok = 1;
2152 GET_BUFFER_SPACE (6);
2153 if (!zero_times_ok)
2154 /* A + loop. */
2155 STORE_JUMP (on_failure_jump_loop, b, b + 6);
2156 else
2157 /* Simple * loops can use on_failure_keep_string_jump
2158 depending on what follows. But since we don't know
2159 that yet, we leave the decision up to
2160 on_failure_jump_smart. */
2161 INSERT_JUMP (simple ? on_failure_jump_smart
2162 : on_failure_jump_loop,
2163 laststart + startoffset, b + 6);
2164 b += 3;
2165 STORE_JUMP (jump, b, laststart + startoffset);
2166 b += 3;
2168 else
2170 /* A simple ? pattern. */
2171 assert (zero_times_ok);
2172 GET_BUFFER_SPACE (3);
2173 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2174 b += 3;
2177 else /* not greedy */
2178 { /* I wish the greedy and non-greedy cases could be merged. */
2180 if (many_times_ok)
2182 /* The non-greedy multiple match looks like a repeat..until:
2183 we only need a conditional jump at the end of the loop */
2184 GET_BUFFER_SPACE (3);
2185 STORE_JUMP (on_failure_jump, b, laststart);
2186 b += 3;
2187 if (zero_times_ok)
2189 /* The repeat...until naturally matches one or more.
2190 To also match zero times, we need to first jump to
2191 the end of the loop (its conditional jump). */
2192 GET_BUFFER_SPACE (3);
2193 INSERT_JUMP (jump, laststart, b);
2194 b += 3;
2197 else
2199 /* non-greedy a?? */
2200 GET_BUFFER_SPACE (6);
2201 INSERT_JUMP (jump, laststart, b + 3);
2202 b += 3;
2203 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2204 b += 3;
2208 pending_exact = 0;
2209 break;
2212 case '.':
2213 laststart = b;
2214 BUF_PUSH (anychar);
2215 break;
2218 case '[':
2220 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2222 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2224 /* Ensure that we have enough space to push a charset: the
2225 opcode, the length count, and the bitset; 34 bytes in all. */
2226 GET_BUFFER_SPACE (34);
2228 laststart = b;
2230 /* We test `*p == '^' twice, instead of using an if
2231 statement, so we only need one BUF_PUSH. */
2232 BUF_PUSH (*p == '^' ? charset_not : charset);
2233 if (*p == '^')
2234 p++;
2236 /* Remember the first position in the bracket expression. */
2237 p1 = p;
2239 /* Push the number of bytes in the bitmap. */
2240 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2242 /* Clear the whole map. */
2243 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2245 /* charset_not matches newline according to a syntax bit. */
2246 if ((re_opcode_t) b[-2] == charset_not
2247 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2248 SET_LIST_BIT ('\n');
2250 /* Read in characters and ranges, setting map bits. */
2251 for (;;)
2253 int len;
2254 boolean escaped_char = false;
2256 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2258 PATFETCH (c);
2260 /* \ might escape characters inside [...] and [^...]. */
2261 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2263 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2265 PATFETCH (c);
2266 escaped_char = true;
2268 else
2270 /* Could be the end of the bracket expression. If it's
2271 not (i.e., when the bracket expression is `[]' so
2272 far), the ']' character bit gets set way below. */
2273 if (c == ']' && p != p1 + 1)
2274 break;
2277 /* If C indicates start of multibyte char, get the
2278 actual character code in C, and set the pattern
2279 pointer P to the next character boundary. */
2280 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2282 PATUNFETCH;
2283 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2284 p += len;
2286 /* What should we do for the character which is
2287 greater than 0x7F, but not BASE_LEADING_CODE_P?
2288 XXX */
2290 /* See if we're at the beginning of a possible character
2291 class. */
2293 else if (!escaped_char &&
2294 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2296 /* Leave room for the null. */
2297 char str[CHAR_CLASS_MAX_LENGTH + 1];
2299 PATFETCH (c);
2300 c1 = 0;
2302 /* If pattern is `[[:'. */
2303 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2305 for (;;)
2307 PATFETCH (c);
2308 if (c == ':' || c == ']' || p == pend
2309 || c1 == CHAR_CLASS_MAX_LENGTH)
2310 break;
2311 str[c1++] = c;
2313 str[c1] = '\0';
2315 /* If isn't a word bracketed by `[:' and `:]':
2316 undo the ending character, the letters, and
2317 leave the leading `:' and `[' (but set bits for
2318 them). */
2319 if (c == ':' && *p == ']')
2321 int ch;
2322 boolean is_alnum = STREQ (str, "alnum");
2323 boolean is_alpha = STREQ (str, "alpha");
2324 boolean is_ascii = STREQ (str, "ascii");
2325 boolean is_blank = STREQ (str, "blank");
2326 boolean is_cntrl = STREQ (str, "cntrl");
2327 boolean is_digit = STREQ (str, "digit");
2328 boolean is_graph = STREQ (str, "graph");
2329 boolean is_lower = STREQ (str, "lower");
2330 boolean is_multibyte = STREQ (str, "multibyte");
2331 boolean is_nonascii = STREQ (str, "nonascii");
2332 boolean is_print = STREQ (str, "print");
2333 boolean is_punct = STREQ (str, "punct");
2334 boolean is_space = STREQ (str, "space");
2335 boolean is_unibyte = STREQ (str, "unibyte");
2336 boolean is_upper = STREQ (str, "upper");
2337 boolean is_word = STREQ (str, "word");
2338 boolean is_xdigit = STREQ (str, "xdigit");
2340 if (!IS_CHAR_CLASS (str))
2341 FREE_STACK_RETURN (REG_ECTYPE);
2343 /* Throw away the ] at the end of the character
2344 class. */
2345 PATFETCH (c);
2347 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2349 /* Most character classes in a multibyte match
2350 just set a flag. Exceptions are is_blank,
2351 is_digit, is_cntrl, and is_xdigit, since
2352 they can only match ASCII characters. We
2353 don't need to handle them for multibyte. */
2355 if (bufp->multibyte)
2357 int bit = 0;
2359 if (is_alnum) bit = BIT_ALNUM;
2360 if (is_alpha) bit = BIT_ALPHA;
2361 if (is_ascii) bit = BIT_ASCII;
2362 if (is_graph) bit = BIT_GRAPH;
2363 if (is_lower) bit = BIT_LOWER;
2364 if (is_multibyte) bit = BIT_MULTIBYTE;
2365 if (is_nonascii) bit = BIT_NONASCII;
2366 if (is_print) bit = BIT_PRINT;
2367 if (is_punct) bit = BIT_PUNCT;
2368 if (is_space) bit = BIT_SPACE;
2369 if (is_unibyte) bit = BIT_UNIBYTE;
2370 if (is_upper) bit = BIT_UPPER;
2371 if (is_word) bit = BIT_WORD;
2372 if (bit)
2373 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2374 bit);
2377 /* Handle character classes for ASCII characters. */
2378 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2380 int translated = TRANSLATE (ch);
2381 /* This was split into 3 if's to
2382 avoid an arbitrary limit in some compiler. */
2383 if ( (is_alnum && ISALNUM (ch))
2384 || (is_alpha && ISALPHA (ch))
2385 || (is_blank && ISBLANK (ch))
2386 || (is_cntrl && ISCNTRL (ch)))
2387 SET_LIST_BIT (translated);
2388 if ( (is_digit && ISDIGIT (ch))
2389 || (is_graph && ISGRAPH (ch))
2390 || (is_lower && ISLOWER (ch))
2391 || (is_print && ISPRINT (ch)))
2392 SET_LIST_BIT (translated);
2393 if ( (is_punct && ISPUNCT (ch))
2394 || (is_space && ISSPACE (ch))
2395 || (is_upper && ISUPPER (ch))
2396 || (is_xdigit && ISXDIGIT (ch)))
2397 SET_LIST_BIT (translated);
2398 if ( (is_ascii && IS_REAL_ASCII (ch))
2399 || (is_nonascii && !IS_REAL_ASCII (ch))
2400 || (is_unibyte && ISUNIBYTE (ch))
2401 || (is_multibyte && !ISUNIBYTE (ch)))
2402 SET_LIST_BIT (translated);
2404 if ( (is_word && ISWORD (ch)))
2405 SET_LIST_BIT (translated);
2408 /* Repeat the loop. */
2409 continue;
2411 else
2413 c1++;
2414 while (c1--)
2415 PATUNFETCH;
2416 SET_LIST_BIT ('[');
2418 /* Because the `:' may starts the range, we
2419 can't simply set bit and repeat the loop.
2420 Instead, just set it to C and handle below. */
2421 c = ':';
2425 if (p < pend && p[0] == '-' && p[1] != ']')
2428 /* Discard the `-'. */
2429 PATFETCH (c1);
2431 /* Fetch the character which ends the range. */
2432 PATFETCH (c1);
2433 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2435 PATUNFETCH;
2436 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2437 p += len;
2440 if (SINGLE_BYTE_CHAR_P (c)
2441 && ! SINGLE_BYTE_CHAR_P (c1))
2443 /* Handle a range such as \177-\377 in multibyte mode.
2444 Split that into two ranges,,
2445 the low one ending at 0237, and the high one
2446 starting at ...040. */
2447 /* Unless I'm missing something,
2448 this line is useless. -sm
2449 int c1_base = (c1 & ~0177) | 040; */
2450 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2451 c1 = 0237;
2453 else if (!SAME_CHARSET_P (c, c1))
2454 FREE_STACK_RETURN (REG_ERANGE);
2456 else
2457 /* Range from C to C. */
2458 c1 = c;
2460 /* Set the range ... */
2461 if (SINGLE_BYTE_CHAR_P (c))
2462 /* ... into bitmap. */
2464 unsigned this_char;
2465 int range_start = c, range_end = c1;
2467 /* If the start is after the end, the range is empty. */
2468 if (range_start > range_end)
2470 if (syntax & RE_NO_EMPTY_RANGES)
2471 FREE_STACK_RETURN (REG_ERANGE);
2472 /* Else, repeat the loop. */
2474 else
2476 for (this_char = range_start; this_char <= range_end;
2477 this_char++)
2478 SET_LIST_BIT (TRANSLATE (this_char));
2481 else
2482 /* ... into range table. */
2483 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2486 /* Discard any (non)matching list bytes that are all 0 at the
2487 end of the map. Decrease the map-length byte too. */
2488 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2489 b[-1]--;
2490 b += b[-1];
2492 /* Build real range table from work area. */
2493 if (RANGE_TABLE_WORK_USED (range_table_work)
2494 || RANGE_TABLE_WORK_BITS (range_table_work))
2496 int i;
2497 int used = RANGE_TABLE_WORK_USED (range_table_work);
2499 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2500 bytes for flags, two for COUNT, and three bytes for
2501 each character. */
2502 GET_BUFFER_SPACE (4 + used * 3);
2504 /* Indicate the existence of range table. */
2505 laststart[1] |= 0x80;
2507 /* Store the character class flag bits into the range table.
2508 If not in emacs, these flag bits are always 0. */
2509 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2510 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2512 STORE_NUMBER_AND_INCR (b, used / 2);
2513 for (i = 0; i < used; i++)
2514 STORE_CHARACTER_AND_INCR
2515 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2518 break;
2521 case '(':
2522 if (syntax & RE_NO_BK_PARENS)
2523 goto handle_open;
2524 else
2525 goto normal_char;
2528 case ')':
2529 if (syntax & RE_NO_BK_PARENS)
2530 goto handle_close;
2531 else
2532 goto normal_char;
2535 case '\n':
2536 if (syntax & RE_NEWLINE_ALT)
2537 goto handle_alt;
2538 else
2539 goto normal_char;
2542 case '|':
2543 if (syntax & RE_NO_BK_VBAR)
2544 goto handle_alt;
2545 else
2546 goto normal_char;
2549 case '{':
2550 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2551 goto handle_interval;
2552 else
2553 goto normal_char;
2556 case '\\':
2557 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2559 /* Do not translate the character after the \, so that we can
2560 distinguish, e.g., \B from \b, even if we normally would
2561 translate, e.g., B to b. */
2562 PATFETCH_RAW (c);
2564 switch (c)
2566 case '(':
2567 if (syntax & RE_NO_BK_PARENS)
2568 goto normal_backslash;
2570 handle_open:
2572 int shy = 0;
2573 if (p+1 < pend)
2575 /* Look for a special (?...) construct */
2576 PATFETCH (c);
2577 if ((syntax & RE_SHY_GROUPS) && c == '?')
2579 PATFETCH (c);
2580 switch (c)
2582 case ':': shy = 1; break;
2583 default:
2584 /* Only (?:...) is supported right now. */
2585 FREE_STACK_RETURN (REG_BADPAT);
2588 else PATUNFETCH;
2591 if (!shy)
2593 bufp->re_nsub++;
2594 regnum++;
2597 if (COMPILE_STACK_FULL)
2599 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2600 compile_stack_elt_t);
2601 if (compile_stack.stack == NULL) return REG_ESPACE;
2603 compile_stack.size <<= 1;
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 = shy ? -regnum : regnum;
2616 /* Do not push a
2617 start_memory for groups beyond the last one we can
2618 represent in the compiled pattern. */
2619 if (regnum <= MAX_REGNUM && !shy)
2620 BUF_PUSH_2 (start_memory, regnum);
2622 compile_stack.avail++;
2624 fixup_alt_jump = 0;
2625 laststart = 0;
2626 begalt = b;
2627 /* If we've reached MAX_REGNUM groups, then this open
2628 won't actually generate any code, so we'll have to
2629 clear pending_exact explicitly. */
2630 pending_exact = 0;
2631 break;
2634 case ')':
2635 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2637 if (COMPILE_STACK_EMPTY)
2639 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2640 goto normal_backslash;
2641 else
2642 FREE_STACK_RETURN (REG_ERPAREN);
2645 handle_close:
2646 FIXUP_ALT_JUMP ();
2648 /* See similar code for backslashed left paren above. */
2649 if (COMPILE_STACK_EMPTY)
2651 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2652 goto normal_char;
2653 else
2654 FREE_STACK_RETURN (REG_ERPAREN);
2657 /* Since we just checked for an empty stack above, this
2658 ``can't happen''. */
2659 assert (compile_stack.avail != 0);
2661 /* We don't just want to restore into `regnum', because
2662 later groups should continue to be numbered higher,
2663 as in `(ab)c(de)' -- the second group is #2. */
2664 regnum_t this_group_regnum;
2666 compile_stack.avail--;
2667 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2668 fixup_alt_jump
2669 = COMPILE_STACK_TOP.fixup_alt_jump
2670 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2671 : 0;
2672 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2673 this_group_regnum = COMPILE_STACK_TOP.regnum;
2674 /* If we've reached MAX_REGNUM groups, then this open
2675 won't actually generate any code, so we'll have to
2676 clear pending_exact explicitly. */
2677 pending_exact = 0;
2679 /* We're at the end of the group, so now we know how many
2680 groups were inside this one. */
2681 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
2682 BUF_PUSH_2 (stop_memory, this_group_regnum);
2684 break;
2687 case '|': /* `\|'. */
2688 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2689 goto normal_backslash;
2690 handle_alt:
2691 if (syntax & RE_LIMITED_OPS)
2692 goto normal_char;
2694 /* Insert before the previous alternative a jump which
2695 jumps to this alternative if the former fails. */
2696 GET_BUFFER_SPACE (3);
2697 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2698 pending_exact = 0;
2699 b += 3;
2701 /* The alternative before this one has a jump after it
2702 which gets executed if it gets matched. Adjust that
2703 jump so it will jump to this alternative's analogous
2704 jump (put in below, which in turn will jump to the next
2705 (if any) alternative's such jump, etc.). The last such
2706 jump jumps to the correct final destination. A picture:
2707 _____ _____
2708 | | | |
2709 | v | v
2710 a | b | c
2712 If we are at `b', then fixup_alt_jump right now points to a
2713 three-byte space after `a'. We'll put in the jump, set
2714 fixup_alt_jump to right after `b', and leave behind three
2715 bytes which we'll fill in when we get to after `c'. */
2717 FIXUP_ALT_JUMP ();
2719 /* Mark and leave space for a jump after this alternative,
2720 to be filled in later either by next alternative or
2721 when know we're at the end of a series of alternatives. */
2722 fixup_alt_jump = b;
2723 GET_BUFFER_SPACE (3);
2724 b += 3;
2726 laststart = 0;
2727 begalt = b;
2728 break;
2731 case '{':
2732 /* If \{ is a literal. */
2733 if (!(syntax & RE_INTERVALS)
2734 /* If we're at `\{' and it's not the open-interval
2735 operator. */
2736 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2737 || (p - 2 == pattern && p == pend))
2738 goto normal_backslash;
2740 handle_interval:
2742 /* If got here, then the syntax allows intervals. */
2744 /* At least (most) this many matches must be made. */
2745 int lower_bound = 0, upper_bound = -1;
2747 beg_interval = p - 1;
2749 if (p == pend)
2751 if (syntax & RE_NO_BK_BRACES)
2752 goto unfetch_interval;
2753 else
2754 FREE_STACK_RETURN (REG_EBRACE);
2757 GET_UNSIGNED_NUMBER (lower_bound);
2759 if (c == ',')
2761 GET_UNSIGNED_NUMBER (upper_bound);
2762 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2764 else
2765 /* Interval such as `{1}' => match exactly once. */
2766 upper_bound = lower_bound;
2768 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2769 || lower_bound > upper_bound)
2771 if (syntax & RE_NO_BK_BRACES)
2772 goto unfetch_interval;
2773 else
2774 FREE_STACK_RETURN (REG_BADBR);
2777 if (!(syntax & RE_NO_BK_BRACES))
2779 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2781 PATFETCH (c);
2784 if (c != '}')
2786 if (syntax & RE_NO_BK_BRACES)
2787 goto unfetch_interval;
2788 else
2789 FREE_STACK_RETURN (REG_BADBR);
2792 /* We just parsed a valid interval. */
2794 /* If it's invalid to have no preceding re. */
2795 if (!laststart)
2797 if (syntax & RE_CONTEXT_INVALID_OPS)
2798 FREE_STACK_RETURN (REG_BADRPT);
2799 else if (syntax & RE_CONTEXT_INDEP_OPS)
2800 laststart = b;
2801 else
2802 goto unfetch_interval;
2805 /* If the upper bound is zero, don't want to succeed at
2806 all; jump from `laststart' to `b + 3', which will be
2807 the end of the buffer after we insert the jump. */
2808 if (upper_bound == 0)
2810 GET_BUFFER_SPACE (3);
2811 INSERT_JUMP (jump, laststart, b + 3);
2812 b += 3;
2815 /* Otherwise, we have a nontrivial interval. When
2816 we're all done, the pattern will look like:
2817 set_number_at <jump count> <upper bound>
2818 set_number_at <succeed_n count> <lower bound>
2819 succeed_n <after jump addr> <succeed_n count>
2820 <body of loop>
2821 jump_n <succeed_n addr> <jump count>
2822 (The upper bound and `jump_n' are omitted if
2823 `upper_bound' is 1, though.) */
2824 else
2825 { /* If the upper bound is > 1, we need to insert
2826 more at the end of the loop. */
2827 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2829 GET_BUFFER_SPACE (nbytes);
2831 /* Initialize lower bound of the `succeed_n', even
2832 though it will be set during matching by its
2833 attendant `set_number_at' (inserted next),
2834 because `re_compile_fastmap' needs to know.
2835 Jump to the `jump_n' we might insert below. */
2836 INSERT_JUMP2 (succeed_n, laststart,
2837 b + 5 + (upper_bound > 1) * 5,
2838 lower_bound);
2839 b += 5;
2841 /* Code to initialize the lower bound. Insert
2842 before the `succeed_n'. The `5' is the last two
2843 bytes of this `set_number_at', plus 3 bytes of
2844 the following `succeed_n'. */
2845 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2846 b += 5;
2848 if (upper_bound > 1)
2849 { /* More than one repetition is allowed, so
2850 append a backward jump to the `succeed_n'
2851 that starts this interval.
2853 When we've reached this during matching,
2854 we'll have matched the interval once, so
2855 jump back only `upper_bound - 1' times. */
2856 STORE_JUMP2 (jump_n, b, laststart + 5,
2857 upper_bound - 1);
2858 b += 5;
2860 /* The location we want to set is the second
2861 parameter of the `jump_n'; that is `b-2' as
2862 an absolute address. `laststart' will be
2863 the `set_number_at' we're about to insert;
2864 `laststart+3' the number to set, the source
2865 for the relative address. But we are
2866 inserting into the middle of the pattern --
2867 so everything is getting moved up by 5.
2868 Conclusion: (b - 2) - (laststart + 3) + 5,
2869 i.e., b - laststart.
2871 We insert this at the beginning of the loop
2872 so that if we fail during matching, we'll
2873 reinitialize the bounds. */
2874 insert_op2 (set_number_at, laststart, b - laststart,
2875 upper_bound - 1, b);
2876 b += 5;
2879 pending_exact = 0;
2880 beg_interval = NULL;
2882 break;
2884 unfetch_interval:
2885 /* If an invalid interval, match the characters as literals. */
2886 assert (beg_interval);
2887 p = beg_interval;
2888 beg_interval = NULL;
2890 /* normal_char and normal_backslash need `c'. */
2891 PATFETCH (c);
2893 if (!(syntax & RE_NO_BK_BRACES))
2895 if (p > pattern && p[-1] == '\\')
2896 goto normal_backslash;
2898 goto normal_char;
2900 #ifdef emacs
2901 /* There is no way to specify the before_dot and after_dot
2902 operators. rms says this is ok. --karl */
2903 case '=':
2904 BUF_PUSH (at_dot);
2905 break;
2907 case 's':
2908 laststart = b;
2909 PATFETCH (c);
2910 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2911 break;
2913 case 'S':
2914 laststart = b;
2915 PATFETCH (c);
2916 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2917 break;
2919 case 'c':
2920 laststart = b;
2921 PATFETCH_RAW (c);
2922 BUF_PUSH_2 (categoryspec, c);
2923 break;
2925 case 'C':
2926 laststart = b;
2927 PATFETCH_RAW (c);
2928 BUF_PUSH_2 (notcategoryspec, c);
2929 break;
2930 #endif /* emacs */
2933 case 'w':
2934 laststart = b;
2935 BUF_PUSH (wordchar);
2936 break;
2939 case 'W':
2940 laststart = b;
2941 BUF_PUSH (notwordchar);
2942 break;
2945 case '<':
2946 BUF_PUSH (wordbeg);
2947 break;
2949 case '>':
2950 BUF_PUSH (wordend);
2951 break;
2953 case 'b':
2954 BUF_PUSH (wordbound);
2955 break;
2957 case 'B':
2958 BUF_PUSH (notwordbound);
2959 break;
2961 case '`':
2962 BUF_PUSH (begbuf);
2963 break;
2965 case '\'':
2966 BUF_PUSH (endbuf);
2967 break;
2969 case '1': case '2': case '3': case '4': case '5':
2970 case '6': case '7': case '8': case '9':
2971 if (syntax & RE_NO_BK_REFS)
2972 goto normal_char;
2974 c1 = c - '0';
2976 if (c1 > regnum)
2977 FREE_STACK_RETURN (REG_ESUBREG);
2979 /* Can't back reference to a subexpression if inside of it. */
2980 if (group_in_compile_stack (compile_stack, c1))
2981 goto normal_char;
2983 laststart = b;
2984 BUF_PUSH_2 (duplicate, c1);
2985 break;
2988 case '+':
2989 case '?':
2990 if (syntax & RE_BK_PLUS_QM)
2991 goto handle_plus;
2992 else
2993 goto normal_backslash;
2995 default:
2996 normal_backslash:
2997 /* You might think it would be useful for \ to mean
2998 not to translate; but if we don't translate it
2999 it will never match anything. */
3000 c = TRANSLATE (c);
3001 goto normal_char;
3003 break;
3006 default:
3007 /* Expects the character in `c'. */
3008 normal_char:
3009 p1 = p - 1; /* P1 points the head of C. */
3010 #ifdef emacs
3011 if (bufp->multibyte)
3013 c = STRING_CHAR (p1, pend - p1);
3014 c = TRANSLATE (c);
3015 /* Set P to the next character boundary. */
3016 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
3018 #endif
3019 /* If no exactn currently being built. */
3020 if (!pending_exact
3022 /* If last exactn not at current position. */
3023 || pending_exact + *pending_exact + 1 != b
3025 /* We have only one byte following the exactn for the count. */
3026 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
3028 /* If followed by a repetition operator. */
3029 || (p != pend && (*p == '*' || *p == '^'))
3030 || ((syntax & RE_BK_PLUS_QM)
3031 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3032 : p != pend && (*p == '+' || *p == '?'))
3033 || ((syntax & RE_INTERVALS)
3034 && ((syntax & RE_NO_BK_BRACES)
3035 ? p != pend && *p == '{'
3036 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3038 /* Start building a new exactn. */
3040 laststart = b;
3042 BUF_PUSH_2 (exactn, 0);
3043 pending_exact = b - 1;
3046 #ifdef emacs
3047 if (! SINGLE_BYTE_CHAR_P (c))
3049 unsigned char str[MAX_MULTIBYTE_LENGTH];
3050 int i = CHAR_STRING (c, str);
3051 int j;
3052 for (j = 0; j < i; j++)
3054 BUF_PUSH (str[j]);
3055 (*pending_exact)++;
3058 else
3059 #endif
3061 BUF_PUSH (c);
3062 (*pending_exact)++;
3064 break;
3065 } /* switch (c) */
3066 } /* while p != pend */
3069 /* Through the pattern now. */
3071 FIXUP_ALT_JUMP ();
3073 if (!COMPILE_STACK_EMPTY)
3074 FREE_STACK_RETURN (REG_EPAREN);
3076 /* If we don't want backtracking, force success
3077 the first time we reach the end of the compiled pattern. */
3078 if (syntax & RE_NO_POSIX_BACKTRACKING)
3079 BUF_PUSH (succeed);
3081 free (compile_stack.stack);
3083 /* We have succeeded; set the length of the buffer. */
3084 bufp->used = b - bufp->buffer;
3086 #ifdef DEBUG
3087 if (debug > 0)
3089 re_compile_fastmap (bufp);
3090 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3091 print_compiled_pattern (bufp);
3093 debug--;
3094 #endif /* DEBUG */
3096 #ifndef MATCH_MAY_ALLOCATE
3097 /* Initialize the failure stack to the largest possible stack. This
3098 isn't necessary unless we're trying to avoid calling alloca in
3099 the search and match routines. */
3101 int num_regs = bufp->re_nsub + 1;
3103 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3105 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3107 if (! fail_stack.stack)
3108 fail_stack.stack
3109 = (fail_stack_elt_t *) malloc (fail_stack.size
3110 * sizeof (fail_stack_elt_t));
3111 else
3112 fail_stack.stack
3113 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3114 (fail_stack.size
3115 * sizeof (fail_stack_elt_t)));
3118 regex_grow_registers (num_regs);
3120 #endif /* not MATCH_MAY_ALLOCATE */
3122 return REG_NOERROR;
3123 } /* regex_compile */
3125 /* Subroutines for `regex_compile'. */
3127 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3129 static void
3130 store_op1 (op, loc, arg)
3131 re_opcode_t op;
3132 unsigned char *loc;
3133 int arg;
3135 *loc = (unsigned char) op;
3136 STORE_NUMBER (loc + 1, arg);
3140 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3142 static void
3143 store_op2 (op, loc, arg1, arg2)
3144 re_opcode_t op;
3145 unsigned char *loc;
3146 int arg1, arg2;
3148 *loc = (unsigned char) op;
3149 STORE_NUMBER (loc + 1, arg1);
3150 STORE_NUMBER (loc + 3, arg2);
3154 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3155 for OP followed by two-byte integer parameter ARG. */
3157 static void
3158 insert_op1 (op, loc, arg, end)
3159 re_opcode_t op;
3160 unsigned char *loc;
3161 int arg;
3162 unsigned char *end;
3164 register unsigned char *pfrom = end;
3165 register unsigned char *pto = end + 3;
3167 while (pfrom != loc)
3168 *--pto = *--pfrom;
3170 store_op1 (op, loc, arg);
3174 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3176 static void
3177 insert_op2 (op, loc, arg1, arg2, end)
3178 re_opcode_t op;
3179 unsigned char *loc;
3180 int arg1, arg2;
3181 unsigned char *end;
3183 register unsigned char *pfrom = end;
3184 register unsigned char *pto = end + 5;
3186 while (pfrom != loc)
3187 *--pto = *--pfrom;
3189 store_op2 (op, loc, arg1, arg2);
3193 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3194 after an alternative or a begin-subexpression. We assume there is at
3195 least one character before the ^. */
3197 static boolean
3198 at_begline_loc_p (pattern, p, syntax)
3199 const unsigned char *pattern, *p;
3200 reg_syntax_t syntax;
3202 const unsigned char *prev = p - 2;
3203 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3205 return
3206 /* After a subexpression? */
3207 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3208 /* After an alternative? */
3209 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3213 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3214 at least one character after the $, i.e., `P < PEND'. */
3216 static boolean
3217 at_endline_loc_p (p, pend, syntax)
3218 const unsigned char *p, *pend;
3219 reg_syntax_t syntax;
3221 const unsigned char *next = p;
3222 boolean next_backslash = *next == '\\';
3223 const unsigned char *next_next = p + 1 < pend ? p + 1 : 0;
3225 return
3226 /* Before a subexpression? */
3227 (syntax & RE_NO_BK_PARENS ? *next == ')'
3228 : next_backslash && next_next && *next_next == ')')
3229 /* Before an alternative? */
3230 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3231 : next_backslash && next_next && *next_next == '|');
3235 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3236 false if it's not. */
3238 static boolean
3239 group_in_compile_stack (compile_stack, regnum)
3240 compile_stack_type compile_stack;
3241 regnum_t regnum;
3243 int this_element;
3245 for (this_element = compile_stack.avail - 1;
3246 this_element >= 0;
3247 this_element--)
3248 if (compile_stack.stack[this_element].regnum == regnum)
3249 return true;
3251 return false;
3254 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3255 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3256 characters can start a string that matches the pattern. This fastmap
3257 is used by re_search to skip quickly over impossible starting points.
3259 Character codes above (1 << BYTEWIDTH) are not represented in the
3260 fastmap, but the leading codes are represented. Thus, the fastmap
3261 indicates which character sets could start a match.
3263 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3264 area as BUFP->fastmap.
3266 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3267 the pattern buffer.
3269 Returns 0 if we succeed, -2 if an internal error. */
3272 re_compile_fastmap (bufp)
3273 struct re_pattern_buffer *bufp;
3275 int j, k;
3276 #ifdef MATCH_MAY_ALLOCATE
3277 fail_stack_type fail_stack;
3278 #endif
3279 #ifndef REGEX_MALLOC
3280 char *destination;
3281 #endif
3283 register char *fastmap = bufp->fastmap;
3284 unsigned char *pattern = bufp->buffer;
3285 unsigned long size = bufp->used;
3286 unsigned char *p = pattern;
3287 register unsigned char *pend = pattern + size;
3289 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
3290 /* This holds the pointer to the failure stack, when
3291 it is allocated relocatably. */
3292 fail_stack_elt_t *failure_stack_ptr;
3293 #endif
3295 /* Assume that each path through the pattern can be null until
3296 proven otherwise. We set this false at the bottom of switch
3297 statement, to which we get only if a particular path doesn't
3298 match the empty string. */
3299 boolean path_can_be_null = true;
3301 /* We aren't doing a `succeed_n' to begin with. */
3302 boolean succeed_n_p = false;
3304 /* If all elements for base leading-codes in fastmap is set, this
3305 flag is set true. */
3306 boolean match_any_multibyte_characters = false;
3308 /* Maximum code of simple (single byte) character. */
3309 int simple_char_max;
3311 assert (fastmap != NULL && p != NULL);
3313 INIT_FAIL_STACK ();
3314 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3315 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3316 bufp->can_be_null = 0;
3318 /* The loop below works as follows:
3319 - It has a working-list kept in the PATTERN_STACK and which basically
3320 starts by only containing a pointer to the first operation.
3321 - If the opcode we're looking at is a match against some set of
3322 chars, then we add those chars to the fastmap and go on to the
3323 next work element from the worklist (done via `break').
3324 - If the opcode is a control operator on the other hand, we either
3325 ignore it (if it's meaningless at this point, such as `start_memory')
3326 or execute it (if it's a jump). If the jump has several destinations
3327 (i.e. `on_failure_jump'), then we push the other destination onto the
3328 worklist.
3329 We guarantee termination by ignoring backward jumps (more or less),
3330 so that `p' is monotonically increasing. More to the point, we
3331 never set `p' (or push) anything `<= p1'. */
3333 /* If can_be_null is set, then the fastmap will not be used anyway. */
3334 while (!bufp->can_be_null)
3336 /* `p1' is used as a marker of how far back a `on_failure_jump'
3337 can go without being ignored. It is normally equal to `p'
3338 (which prevents any backward `on_failure_jump') except right
3339 after a plain `jump', to allow patterns such as:
3340 0: jump 10
3341 3..9: <body>
3342 10: on_failure_jump 3
3343 as used for the *? operator. */
3344 unsigned char *p1 = p;
3346 if (p == pend || *p == succeed)
3348 /* We have reached the (effective) end of pattern. */
3349 if (!PATTERN_STACK_EMPTY ())
3351 bufp->can_be_null |= path_can_be_null;
3353 /* Reset for next path. */
3354 path_can_be_null = true;
3356 p = (unsigned char*) POP_PATTERN_OP ();
3358 continue;
3360 else
3361 break;
3364 /* We should never be about to go beyond the end of the pattern. */
3365 assert (p < pend);
3367 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3370 case duplicate:
3371 /* If the first character has to match a backreference, that means
3372 that the group was empty (since it already matched). Since this
3373 is the only case that interests us here, we can assume that the
3374 backreference must match the empty string. */
3375 p++;
3376 continue;
3379 /* Following are the cases which match a character. These end
3380 with `break'. */
3382 case exactn:
3383 fastmap[p[1]] = 1;
3384 break;
3387 #ifndef emacs
3388 case charset:
3390 int length = (*p & 0x7f);;
3391 p++;
3393 for (j = length * BYTEWIDTH - 1; j >= 0; j--)
3394 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3395 fastmap[j] = 1;
3397 break;
3399 case charset_not:
3400 /* Chars beyond end of map must be allowed. */
3402 int length = (*p & 0x7f);;
3403 p++;
3405 for (j = length * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
3406 fastmap[j] = 1;
3408 for (j = length * BYTEWIDTH - 1; j >= 0; j--)
3409 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3410 fastmap[j] = 1;
3412 break;
3414 case wordchar:
3415 for (j = 0; j < (1 << BYTEWIDTH); j++)
3416 if (SYNTAX (j) == Sword)
3417 fastmap[j] = 1;
3418 break;
3421 case notwordchar:
3422 for (j = 0; j < (1 << BYTEWIDTH); j++)
3423 if (SYNTAX (j) != Sword)
3424 fastmap[j] = 1;
3425 break;
3426 #else /* emacs */
3427 case charset:
3428 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3429 j >= 0; j--)
3430 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
3431 fastmap[j] = 1;
3433 /* If we can match a character class, we can match
3434 any character set. */
3435 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3436 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0)
3437 goto set_fastmap_for_multibyte_characters;
3439 if (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3440 && match_any_multibyte_characters == false)
3442 /* Set fastmap[I] 1 where I is a base leading code of each
3443 multibyte character in the range table. */
3444 int c, count;
3446 /* Make P points the range table. */
3447 p += CHARSET_BITMAP_SIZE (&p[-2]);
3449 /* Extract the number of ranges in range table into COUNT. */
3450 EXTRACT_NUMBER_AND_INCR (count, p);
3451 for (; count > 0; count--, p += 2 * 3) /* XXX */
3453 /* Extract the start of each range. */
3454 EXTRACT_CHARACTER (c, p);
3455 j = CHAR_CHARSET (c);
3456 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3459 break;
3462 case charset_not:
3463 /* Chars beyond end of bitmap are possible matches.
3464 All the single-byte codes can occur in multibyte buffers.
3465 So any that are not listed in the charset
3466 are possible matches, even in multibyte buffers. */
3467 simple_char_max = (1 << BYTEWIDTH);
3468 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3469 j < simple_char_max; j++)
3470 fastmap[j] = 1;
3472 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3473 j >= 0; j--)
3474 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
3475 fastmap[j] = 1;
3477 if (bufp->multibyte)
3478 /* Any character set can possibly contain a character
3479 which doesn't match the specified set of characters. */
3481 set_fastmap_for_multibyte_characters:
3482 if (match_any_multibyte_characters == false)
3484 for (j = 0x80; j < 0xA0; j++) /* XXX */
3485 if (BASE_LEADING_CODE_P (j))
3486 fastmap[j] = 1;
3487 match_any_multibyte_characters = true;
3490 break;
3493 case wordchar:
3494 /* All the single-byte codes can occur in multibyte buffers,
3495 and they may have word syntax. So do consider them. */
3496 simple_char_max = (1 << BYTEWIDTH);
3497 for (j = 0; j < simple_char_max; j++)
3498 if (SYNTAX (j) == Sword)
3499 fastmap[j] = 1;
3501 if (bufp->multibyte)
3502 /* Any character set can possibly contain a character
3503 whose syntax is `Sword'. */
3504 goto set_fastmap_for_multibyte_characters;
3505 break;
3508 case notwordchar:
3509 /* All the single-byte codes can occur in multibyte buffers,
3510 and they may not have word syntax. So do consider them. */
3511 simple_char_max = (1 << BYTEWIDTH);
3512 for (j = 0; j < simple_char_max; j++)
3513 if (SYNTAX (j) != Sword)
3514 fastmap[j] = 1;
3516 if (bufp->multibyte)
3517 /* Any character set can possibly contain a character
3518 whose syntax is not `Sword'. */
3519 goto set_fastmap_for_multibyte_characters;
3520 break;
3521 #endif
3523 case anychar:
3525 int fastmap_newline = fastmap['\n'];
3527 /* `.' matches anything, except perhaps newline.
3528 Even in a multibyte buffer, it should match any
3529 conceivable byte value for the fastmap. */
3530 if (bufp->multibyte)
3531 match_any_multibyte_characters = true;
3533 simple_char_max = (1 << BYTEWIDTH);
3534 for (j = 0; j < simple_char_max; j++)
3535 fastmap[j] = 1;
3537 /* ... except perhaps newline. */
3538 if (!(bufp->syntax & RE_DOT_NEWLINE))
3539 fastmap['\n'] = fastmap_newline;
3541 /* Otherwise, have to check alternative paths. */
3542 break;
3545 #ifdef emacs
3546 case wordbound:
3547 case notwordbound:
3548 case wordbeg:
3549 case wordend:
3550 case notsyntaxspec:
3551 case syntaxspec:
3552 /* This match depends on text properties. These end with
3553 aborting optimizations. */
3554 bufp->can_be_null = 1;
3555 continue;
3556 #if 0
3557 k = *p++;
3558 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3559 for (j = 0; j < simple_char_max; j++)
3560 if (SYNTAX (j) == (enum syntaxcode) k)
3561 fastmap[j] = 1;
3563 if (bufp->multibyte)
3564 /* Any character set can possibly contain a character
3565 whose syntax is K. */
3566 goto set_fastmap_for_multibyte_characters;
3567 break;
3569 case notsyntaxspec:
3570 k = *p++;
3571 simple_char_max = bufp->multibyte ? 0x80 : (1 << BYTEWIDTH);
3572 for (j = 0; j < simple_char_max; j++)
3573 if (SYNTAX (j) != (enum syntaxcode) k)
3574 fastmap[j] = 1;
3576 if (bufp->multibyte)
3577 /* Any character set can possibly contain a character
3578 whose syntax is not K. */
3579 goto set_fastmap_for_multibyte_characters;
3580 break;
3581 #endif
3584 case categoryspec:
3585 k = *p++;
3586 simple_char_max = (1 << BYTEWIDTH);
3587 for (j = 0; j < simple_char_max; j++)
3588 if (CHAR_HAS_CATEGORY (j, k))
3589 fastmap[j] = 1;
3591 if (bufp->multibyte)
3592 /* Any character set can possibly contain a character
3593 whose category is K. */
3594 goto set_fastmap_for_multibyte_characters;
3595 break;
3598 case notcategoryspec:
3599 k = *p++;
3600 simple_char_max = (1 << BYTEWIDTH);
3601 for (j = 0; j < simple_char_max; j++)
3602 if (!CHAR_HAS_CATEGORY (j, k))
3603 fastmap[j] = 1;
3605 if (bufp->multibyte)
3606 /* Any character set can possibly contain a character
3607 whose category is not K. */
3608 goto set_fastmap_for_multibyte_characters;
3609 break;
3611 /* All cases after this match the empty string. These end with
3612 `continue'. */
3615 case before_dot:
3616 case at_dot:
3617 case after_dot:
3618 continue;
3619 #endif /* emacs */
3622 case no_op:
3623 case begline:
3624 case endline:
3625 case begbuf:
3626 case endbuf:
3627 #ifndef emacs
3628 case wordbound:
3629 case notwordbound:
3630 case wordbeg:
3631 case wordend:
3632 #endif
3633 continue;
3636 case jump_n:
3637 case jump:
3638 EXTRACT_NUMBER_AND_INCR (j, p);
3639 if (j < 0)
3640 /* Backward jumps can only go back to code that we've already
3641 visited. `re_compile' should make sure this is true. */
3642 break;
3643 p += j;
3644 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3646 case on_failure_jump:
3647 case on_failure_keep_string_jump:
3648 case on_failure_jump_loop:
3649 case on_failure_jump_smart:
3650 p++;
3651 break;
3652 default:
3653 continue;
3655 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3656 to jump back to "just after here". */
3657 /* Fallthrough */
3659 case on_failure_jump:
3660 case on_failure_keep_string_jump:
3661 case on_failure_jump_loop:
3662 case on_failure_jump_smart:
3663 handle_on_failure_jump:
3664 EXTRACT_NUMBER_AND_INCR (j, p);
3666 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3667 end of the pattern. We don't want to push such a point,
3668 since when we restore it above, entering the switch will
3669 increment `p' past the end of the pattern. We don't need
3670 to push such a point since we obviously won't find any more
3671 fastmap entries beyond `pend'. Such a pattern can match
3672 the null string, though. */
3673 if (p + j <= p1)
3674 /* Backward jump to be ignored. */
3676 else if (p + j < pend)
3678 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3680 RESET_FAIL_STACK ();
3681 return -2;
3684 else
3685 bufp->can_be_null = 1;
3687 if (succeed_n_p)
3689 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3690 succeed_n_p = false;
3693 continue;
3696 case succeed_n:
3697 /* Get to the number of times to succeed. */
3698 p += 2;
3700 /* Increment p past the n for when k != 0. */
3701 EXTRACT_NUMBER_AND_INCR (k, p);
3702 if (k == 0)
3704 p -= 4;
3705 succeed_n_p = true; /* Spaghetti code alert. */
3706 goto handle_on_failure_jump;
3708 continue;
3711 case set_number_at:
3712 p += 4;
3713 continue;
3716 case start_memory:
3717 case stop_memory:
3718 p += 1;
3719 continue;
3722 default:
3723 abort (); /* We have listed all the cases. */
3724 } /* switch *p++ */
3726 /* Getting here means we have found the possible starting
3727 characters for one path of the pattern -- and that the empty
3728 string does not match. We need not follow this path further.
3729 Instead, look at the next alternative (remembered on the
3730 stack), or quit if no more. The test at the top of the loop
3731 does these things. */
3732 path_can_be_null = false;
3733 p = pend;
3734 } /* while p */
3736 /* Set `can_be_null' for the last path (also the first path, if the
3737 pattern is empty). */
3738 bufp->can_be_null |= path_can_be_null;
3739 RESET_FAIL_STACK ();
3740 return 0;
3741 } /* re_compile_fastmap */
3743 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3744 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3745 this memory for recording register information. STARTS and ENDS
3746 must be allocated using the malloc library routine, and must each
3747 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3749 If NUM_REGS == 0, then subsequent matches should allocate their own
3750 register data.
3752 Unless this function is called, the first search or match using
3753 PATTERN_BUFFER will allocate its own register data, without
3754 freeing the old data. */
3756 void
3757 re_set_registers (bufp, regs, num_regs, starts, ends)
3758 struct re_pattern_buffer *bufp;
3759 struct re_registers *regs;
3760 unsigned num_regs;
3761 regoff_t *starts, *ends;
3763 if (num_regs)
3765 bufp->regs_allocated = REGS_REALLOCATE;
3766 regs->num_regs = num_regs;
3767 regs->start = starts;
3768 regs->end = ends;
3770 else
3772 bufp->regs_allocated = REGS_UNALLOCATED;
3773 regs->num_regs = 0;
3774 regs->start = regs->end = (regoff_t *) 0;
3778 /* Searching routines. */
3780 /* Like re_search_2, below, but only one string is specified, and
3781 doesn't let you say where to stop matching. */
3784 re_search (bufp, string, size, startpos, range, regs)
3785 struct re_pattern_buffer *bufp;
3786 const char *string;
3787 int size, startpos, range;
3788 struct re_registers *regs;
3790 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3791 regs, size);
3794 /* End address of virtual concatenation of string. */
3795 #define STOP_ADDR_VSTRING(P) \
3796 (((P) >= size1 ? string2 + size2 : string1 + size1))
3798 /* Address of POS in the concatenation of virtual string. */
3799 #define POS_ADDR_VSTRING(POS) \
3800 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3802 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3803 virtual concatenation of STRING1 and STRING2, starting first at index
3804 STARTPOS, then at STARTPOS + 1, and so on.
3806 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3808 RANGE is how far to scan while trying to match. RANGE = 0 means try
3809 only at STARTPOS; in general, the last start tried is STARTPOS +
3810 RANGE.
3812 In REGS, return the indices of the virtual concatenation of STRING1
3813 and STRING2 that matched the entire BUFP->buffer and its contained
3814 subexpressions.
3816 Do not consider matching one past the index STOP in the virtual
3817 concatenation of STRING1 and STRING2.
3819 We return either the position in the strings at which the match was
3820 found, -1 if no match, or -2 if error (such as failure
3821 stack overflow). */
3824 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
3825 struct re_pattern_buffer *bufp;
3826 const char *str1, *str2;
3827 int size1, size2;
3828 int startpos;
3829 int range;
3830 struct re_registers *regs;
3831 int stop;
3833 int val;
3834 re_char *string1 = (re_char*) str1;
3835 re_char *string2 = (re_char*) str2;
3836 register char *fastmap = bufp->fastmap;
3837 register RE_TRANSLATE_TYPE translate = bufp->translate;
3838 int total_size = size1 + size2;
3839 int endpos = startpos + range;
3840 int anchored_start = 0;
3842 /* Nonzero if we have to concern multibyte character. */
3843 int multibyte = bufp->multibyte;
3845 /* Check for out-of-range STARTPOS. */
3846 if (startpos < 0 || startpos > total_size)
3847 return -1;
3849 /* Fix up RANGE if it might eventually take us outside
3850 the virtual concatenation of STRING1 and STRING2.
3851 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3852 if (endpos < 0)
3853 range = 0 - startpos;
3854 else if (endpos > total_size)
3855 range = total_size - startpos;
3857 /* If the search isn't to be a backwards one, don't waste time in a
3858 search for a pattern anchored at beginning of buffer. */
3859 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3861 if (startpos > 0)
3862 return -1;
3863 else
3864 range = 0;
3867 #ifdef emacs
3868 /* In a forward search for something that starts with \=.
3869 don't keep searching past point. */
3870 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3872 range = PT_BYTE - BEGV_BYTE - startpos;
3873 if (range < 0)
3874 return -1;
3876 #endif /* emacs */
3878 /* Update the fastmap now if not correct already. */
3879 if (fastmap && !bufp->fastmap_accurate)
3880 if (re_compile_fastmap (bufp) == -2)
3881 return -2;
3883 /* See whether the pattern is anchored. */
3884 if (bufp->buffer[0] == begline)
3885 anchored_start = 1;
3887 #ifdef emacs
3888 gl_state.object = re_match_object;
3890 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
3892 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3894 #endif
3896 /* Loop through the string, looking for a place to start matching. */
3897 for (;;)
3899 /* If the pattern is anchored,
3900 skip quickly past places we cannot match.
3901 We don't bother to treat startpos == 0 specially
3902 because that case doesn't repeat. */
3903 if (anchored_start && startpos > 0)
3905 if (! (bufp->newline_anchor
3906 && ((startpos <= size1 ? string1[startpos - 1]
3907 : string2[startpos - size1 - 1])
3908 == '\n')))
3909 goto advance;
3912 /* If a fastmap is supplied, skip quickly over characters that
3913 cannot be the start of a match. If the pattern can match the
3914 null string, however, we don't need to skip characters; we want
3915 the first null string. */
3916 if (fastmap && startpos < total_size && !bufp->can_be_null)
3918 register re_char *d;
3919 register unsigned int buf_ch;
3921 d = POS_ADDR_VSTRING (startpos);
3923 if (range > 0) /* Searching forwards. */
3925 register int lim = 0;
3926 int irange = range;
3928 if (startpos < size1 && startpos + range >= size1)
3929 lim = range - (size1 - startpos);
3931 /* Written out as an if-else to avoid testing `translate'
3932 inside the loop. */
3933 if (RE_TRANSLATE_P (translate))
3935 if (multibyte)
3936 while (range > lim)
3938 int buf_charlen;
3940 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3941 buf_charlen);
3943 buf_ch = RE_TRANSLATE (translate, buf_ch);
3944 if (buf_ch >= 0400
3945 || fastmap[buf_ch])
3946 break;
3948 range -= buf_charlen;
3949 d += buf_charlen;
3951 else
3952 while (range > lim
3953 && !fastmap[RE_TRANSLATE (translate, *d)])
3955 d++;
3956 range--;
3959 else
3960 while (range > lim && !fastmap[*d])
3962 d++;
3963 range--;
3966 startpos += irange - range;
3968 else /* Searching backwards. */
3970 buf_ch = STRING_CHAR (d, (startpos >= size1
3971 ? size2 + size1 - startpos
3972 : size1 - startpos));
3973 if (RE_TRANSLATE_P (translate))
3974 buf_ch = RE_TRANSLATE (translate, buf_ch);
3976 if (! (buf_ch >= 0400
3977 || fastmap[buf_ch]))
3978 goto advance;
3982 /* If can't match the null string, and that's all we have left, fail. */
3983 if (range >= 0 && startpos == total_size && fastmap
3984 && !bufp->can_be_null)
3985 return -1;
3987 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3988 startpos, regs, stop);
3989 #ifndef REGEX_MALLOC
3990 #ifdef C_ALLOCA
3991 alloca (0);
3992 #endif
3993 #endif
3995 if (val >= 0)
3996 return startpos;
3998 if (val == -2)
3999 return -2;
4001 advance:
4002 if (!range)
4003 break;
4004 else if (range > 0)
4006 /* Update STARTPOS to the next character boundary. */
4007 if (multibyte)
4009 re_char *p = POS_ADDR_VSTRING (startpos);
4010 re_char *pend = STOP_ADDR_VSTRING (startpos);
4011 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
4013 range -= len;
4014 if (range < 0)
4015 break;
4016 startpos += len;
4018 else
4020 range--;
4021 startpos++;
4024 else
4026 range++;
4027 startpos--;
4029 /* Update STARTPOS to the previous character boundary. */
4030 if (multibyte)
4032 re_char *p = POS_ADDR_VSTRING (startpos);
4033 int len = 0;
4035 /* Find the head of multibyte form. */
4036 while (!CHAR_HEAD_P (*p))
4037 p--, len++;
4039 /* Adjust it. */
4040 #if 0 /* XXX */
4041 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
4043 else
4044 #endif
4046 range += len;
4047 if (range > 0)
4048 break;
4050 startpos -= len;
4055 return -1;
4056 } /* re_search_2 */
4058 /* Declarations and macros for re_match_2. */
4060 static int bcmp_translate ();
4062 /* This converts PTR, a pointer into one of the search strings `string1'
4063 and `string2' into an offset from the beginning of that string. */
4064 #define POINTER_TO_OFFSET(ptr) \
4065 (FIRST_STRING_P (ptr) \
4066 ? ((regoff_t) ((ptr) - string1)) \
4067 : ((regoff_t) ((ptr) - string2 + size1)))
4069 /* Call before fetching a character with *d. This switches over to
4070 string2 if necessary. */
4071 #define PREFETCH() \
4072 while (d == dend) \
4074 /* End of string2 => fail. */ \
4075 if (dend == end_match_2) \
4076 goto fail; \
4077 /* End of string1 => advance to string2. */ \
4078 d = string2; \
4079 dend = end_match_2; \
4083 /* Test if at very beginning or at very end of the virtual concatenation
4084 of `string1' and `string2'. If only one string, it's `string2'. */
4085 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4086 #define AT_STRINGS_END(d) ((d) == end2)
4089 /* Test if D points to a character which is word-constituent. We have
4090 two special cases to check for: if past the end of string1, look at
4091 the first character in string2; and if before the beginning of
4092 string2, look at the last character in string1. */
4093 #define WORDCHAR_P(d) \
4094 (SYNTAX ((d) == end1 ? *string2 \
4095 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4096 == Sword)
4098 /* Disabled due to a compiler bug -- see comment at case wordbound */
4100 /* The comment at case wordbound is following one, but we don't use
4101 AT_WORD_BOUNDARY anymore to support multibyte form.
4103 The DEC Alpha C compiler 3.x generates incorrect code for the
4104 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4105 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4106 macro and introducing temporary variables works around the bug. */
4108 #if 0
4109 /* Test if the character before D and the one at D differ with respect
4110 to being word-constituent. */
4111 #define AT_WORD_BOUNDARY(d) \
4112 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4113 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4114 #endif
4116 /* Free everything we malloc. */
4117 #ifdef MATCH_MAY_ALLOCATE
4118 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4119 #define FREE_VARIABLES() \
4120 do { \
4121 REGEX_FREE_STACK (fail_stack.stack); \
4122 FREE_VAR (regstart); \
4123 FREE_VAR (regend); \
4124 FREE_VAR (best_regstart); \
4125 FREE_VAR (best_regend); \
4126 } while (0)
4127 #else
4128 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4129 #endif /* not MATCH_MAY_ALLOCATE */
4132 /* Optimization routines. */
4134 /* If the operation is a match against one or more chars,
4135 return a pointer to the next operation, else return NULL. */
4136 static unsigned char *
4137 skip_one_char (p)
4138 unsigned char *p;
4140 switch (SWITCH_ENUM_CAST (*p++))
4142 case anychar:
4143 break;
4145 case exactn:
4146 p += *p + 1;
4147 break;
4149 case charset_not:
4150 case charset:
4151 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4153 int mcnt;
4154 p = CHARSET_RANGE_TABLE (p - 1);
4155 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4156 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4158 else
4159 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4160 break;
4162 #ifdef emacs
4163 case syntaxspec:
4164 case notsyntaxspec:
4165 case categoryspec:
4166 case notcategoryspec:
4167 #endif /* emacs */
4168 p++;
4169 break;
4171 default:
4172 p = NULL;
4174 return p;
4178 /* Jump over non-matching operations. */
4179 static unsigned char *
4180 skip_noops (p, pend)
4181 unsigned char *p, *pend;
4183 int mcnt;
4184 while (p < pend)
4186 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4188 case start_memory:
4189 case stop_memory:
4190 p += 2; break;
4191 case no_op:
4192 p += 1; break;
4193 case jump:
4194 p += 1;
4195 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4196 p += mcnt;
4197 break;
4198 default:
4199 return p;
4202 assert (p == pend);
4203 return p;
4206 /* Non-zero if "p1 matches something" implies "p2 fails". */
4207 static int
4208 mutually_exclusive_p (bufp, p1, p2)
4209 struct re_pattern_buffer *bufp;
4210 unsigned char *p1, *p2;
4212 re_opcode_t op2;
4213 const boolean multibyte = bufp->multibyte;
4214 unsigned char *pend = bufp->buffer + bufp->used;
4216 assert (p1 >= bufp->buffer && p1 < pend
4217 && p2 >= bufp->buffer && p2 <= pend);
4219 /* Skip over open/close-group commands.
4220 If what follows this loop is a ...+ construct,
4221 look at what begins its body, since we will have to
4222 match at least one of that. */
4223 p2 = skip_noops (p2, pend);
4224 /* The same skip can be done for p1, except that this function
4225 is only used in the case where p1 is a simple match operator. */
4226 /* p1 = skip_noops (p1, pend); */
4228 assert (p1 >= bufp->buffer && p1 < pend
4229 && p2 >= bufp->buffer && p2 <= pend);
4231 op2 = p2 == pend ? succeed : *p2;
4233 switch (SWITCH_ENUM_CAST (op2))
4235 case succeed:
4236 case endbuf:
4237 /* If we're at the end of the pattern, we can change. */
4238 if (skip_one_char (p1))
4240 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4241 return 1;
4243 break;
4245 case endline:
4246 if (!bufp->newline_anchor)
4247 break;
4248 /* Fallthrough */
4249 case exactn:
4251 register unsigned int c
4252 = (re_opcode_t) *p2 == endline ? '\n'
4253 : RE_STRING_CHAR(p2 + 2, pend - p2 - 2);
4255 if ((re_opcode_t) *p1 == exactn)
4257 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4259 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4260 return 1;
4264 else if ((re_opcode_t) *p1 == charset
4265 || (re_opcode_t) *p1 == charset_not)
4267 int not = (re_opcode_t) *p1 == charset_not;
4269 /* Test if C is listed in charset (or charset_not)
4270 at `p1'. */
4271 if (SINGLE_BYTE_CHAR_P (c))
4273 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4274 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4275 not = !not;
4277 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4278 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4280 /* `not' is equal to 1 if c would match, which means
4281 that we can't change to pop_failure_jump. */
4282 if (!not)
4284 DEBUG_PRINT1 (" No match => fast loop.\n");
4285 return 1;
4288 else if ((re_opcode_t) *p1 == anychar
4289 && c == '\n')
4291 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4292 return 1;
4295 break;
4297 case charset:
4298 case charset_not:
4300 if ((re_opcode_t) *p1 == exactn)
4301 /* Reuse the code above. */
4302 return mutually_exclusive_p (bufp, p2, p1);
4305 /* It is hard to list up all the character in charset
4306 P2 if it includes multibyte character. Give up in
4307 such case. */
4308 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4310 /* Now, we are sure that P2 has no range table.
4311 So, for the size of bitmap in P2, `p2[1]' is
4312 enough. But P1 may have range table, so the
4313 size of bitmap table of P1 is extracted by
4314 using macro `CHARSET_BITMAP_SIZE'.
4316 Since we know that all the character listed in
4317 P2 is ASCII, it is enough to test only bitmap
4318 table of P1. */
4320 if (*p1 == *p2)
4322 int idx;
4323 /* We win if the charset inside the loop
4324 has no overlap with the one after the loop. */
4325 for (idx = 0;
4326 (idx < (int) p2[1]
4327 && idx < CHARSET_BITMAP_SIZE (p1));
4328 idx++)
4329 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4330 break;
4332 if (idx == p2[1]
4333 || idx == CHARSET_BITMAP_SIZE (p1))
4335 DEBUG_PRINT1 (" No match => fast loop.\n");
4336 return 1;
4339 else if ((re_opcode_t) *p1 == charset
4340 || (re_opcode_t) *p1 == charset_not)
4342 int idx;
4343 /* We win if the charset_not inside the loop lists
4344 every character listed in the charset after. */
4345 for (idx = 0; idx < (int) p2[1]; idx++)
4346 if (! (p2[2 + idx] == 0
4347 || (idx < CHARSET_BITMAP_SIZE (p1)
4348 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4349 break;
4351 if (idx == p2[1])
4353 DEBUG_PRINT1 (" No match => fast loop.\n");
4354 return 1;
4360 #ifdef emacs
4361 case wordend:
4362 case notsyntaxspec:
4363 return ((re_opcode_t) *p1 == syntaxspec
4364 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4366 case wordbeg:
4367 case syntaxspec:
4368 return ((re_opcode_t) *p1 == notsyntaxspec
4369 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4371 case wordbound:
4372 return (((re_opcode_t) *p1 == notsyntaxspec
4373 || (re_opcode_t) *p1 == syntaxspec)
4374 && p1[1] == Sword);
4376 case categoryspec:
4377 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4378 case notcategoryspec:
4379 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4380 #endif /* emacs */
4382 default:
4386 /* Safe default. */
4387 return 0;
4391 /* Matching routines. */
4393 #ifndef emacs /* Emacs never uses this. */
4394 /* re_match is like re_match_2 except it takes only a single string. */
4397 re_match (bufp, string, size, pos, regs)
4398 struct re_pattern_buffer *bufp;
4399 const char *string;
4400 int size, pos;
4401 struct re_registers *regs;
4403 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4404 pos, regs, size);
4405 alloca (0);
4406 return result;
4408 #endif /* not emacs */
4410 #ifdef emacs
4411 /* In Emacs, this is the string or buffer in which we
4412 are matching. It is used for looking up syntax properties. */
4413 Lisp_Object re_match_object;
4414 #endif
4416 /* re_match_2 matches the compiled pattern in BUFP against the
4417 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4418 and SIZE2, respectively). We start matching at POS, and stop
4419 matching at STOP.
4421 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4422 store offsets for the substring each group matched in REGS. See the
4423 documentation for exactly how many groups we fill.
4425 We return -1 if no match, -2 if an internal error (such as the
4426 failure stack overflowing). Otherwise, we return the length of the
4427 matched substring. */
4430 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4431 struct re_pattern_buffer *bufp;
4432 const char *string1, *string2;
4433 int size1, size2;
4434 int pos;
4435 struct re_registers *regs;
4436 int stop;
4438 int result;
4440 #ifdef emacs
4441 int charpos;
4442 gl_state.object = re_match_object;
4443 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4444 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4445 #endif
4447 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4448 pos, regs, stop);
4449 alloca (0);
4450 return result;
4453 /* This is a separate function so that we can force an alloca cleanup
4454 afterwards. */
4455 static int
4456 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4457 struct re_pattern_buffer *bufp;
4458 re_char *string1, *string2;
4459 int size1, size2;
4460 int pos;
4461 struct re_registers *regs;
4462 int stop;
4464 /* General temporaries. */
4465 int mcnt;
4466 boolean not;
4467 unsigned char *p1;
4469 /* Just past the end of the corresponding string. */
4470 re_char *end1, *end2;
4472 /* Pointers into string1 and string2, just past the last characters in
4473 each to consider matching. */
4474 re_char *end_match_1, *end_match_2;
4476 /* Where we are in the data, and the end of the current string. */
4477 re_char *d, *dend;
4479 /* Used sometimes to remember where we were before starting matching
4480 an operator so that we can go back in case of failure. This "atomic"
4481 behavior of matching opcodes is indispensable to the correctness
4482 of the on_failure_keep_string_jump optimization. */
4483 re_char *dfail;
4485 /* Where we are in the pattern, and the end of the pattern. */
4486 unsigned char *p = bufp->buffer;
4487 register unsigned char *pend = p + bufp->used;
4489 /* We use this to map every character in the string. */
4490 RE_TRANSLATE_TYPE translate = bufp->translate;
4492 /* Nonzero if we have to concern multibyte character. */
4493 int multibyte = bufp->multibyte;
4495 /* Failure point stack. Each place that can handle a failure further
4496 down the line pushes a failure point on this stack. It consists of
4497 regstart, and regend for all registers corresponding to
4498 the subexpressions we're currently inside, plus the number of such
4499 registers, and, finally, two char *'s. The first char * is where
4500 to resume scanning the pattern; the second one is where to resume
4501 scanning the strings. */
4502 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4503 fail_stack_type fail_stack;
4504 #endif
4505 #ifdef DEBUG
4506 static unsigned failure_id = 0;
4507 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4508 #endif
4510 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
4511 /* This holds the pointer to the failure stack, when
4512 it is allocated relocatably. */
4513 fail_stack_elt_t *failure_stack_ptr;
4514 #endif
4516 /* We fill all the registers internally, independent of what we
4517 return, for use in backreferences. The number here includes
4518 an element for register zero. */
4519 unsigned num_regs = bufp->re_nsub + 1;
4521 /* Information on the contents of registers. These are pointers into
4522 the input strings; they record just what was matched (on this
4523 attempt) by a subexpression part of the pattern, that is, the
4524 regnum-th regstart pointer points to where in the pattern we began
4525 matching and the regnum-th regend points to right after where we
4526 stopped matching the regnum-th subexpression. (The zeroth register
4527 keeps track of what the whole pattern matches.) */
4528 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4529 re_char **regstart, **regend;
4530 #endif
4532 /* The following record the register info as found in the above
4533 variables when we find a match better than any we've seen before.
4534 This happens as we backtrack through the failure points, which in
4535 turn happens only if we have not yet matched the entire string. */
4536 unsigned best_regs_set = false;
4537 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4538 re_char **best_regstart, **best_regend;
4539 #endif
4541 /* Logically, this is `best_regend[0]'. But we don't want to have to
4542 allocate space for that if we're not allocating space for anything
4543 else (see below). Also, we never need info about register 0 for
4544 any of the other register vectors, and it seems rather a kludge to
4545 treat `best_regend' differently than the rest. So we keep track of
4546 the end of the best match so far in a separate variable. We
4547 initialize this to NULL so that when we backtrack the first time
4548 and need to test it, it's not garbage. */
4549 re_char *match_end = NULL;
4551 #ifdef DEBUG
4552 /* Counts the total number of registers pushed. */
4553 unsigned num_regs_pushed = 0;
4554 #endif
4556 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4558 INIT_FAIL_STACK ();
4560 #ifdef MATCH_MAY_ALLOCATE
4561 /* Do not bother to initialize all the register variables if there are
4562 no groups in the pattern, as it takes a fair amount of time. If
4563 there are groups, we include space for register 0 (the whole
4564 pattern), even though we never use it, since it simplifies the
4565 array indexing. We should fix this. */
4566 if (bufp->re_nsub)
4568 regstart = REGEX_TALLOC (num_regs, re_char *);
4569 regend = REGEX_TALLOC (num_regs, re_char *);
4570 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4571 best_regend = REGEX_TALLOC (num_regs, re_char *);
4573 if (!(regstart && regend && best_regstart && best_regend))
4575 FREE_VARIABLES ();
4576 return -2;
4579 else
4581 /* We must initialize all our variables to NULL, so that
4582 `FREE_VARIABLES' doesn't try to free them. */
4583 regstart = regend = best_regstart = best_regend = NULL;
4585 #endif /* MATCH_MAY_ALLOCATE */
4587 /* The starting position is bogus. */
4588 if (pos < 0 || pos > size1 + size2)
4590 FREE_VARIABLES ();
4591 return -1;
4594 /* Initialize subexpression text positions to -1 to mark ones that no
4595 start_memory/stop_memory has been seen for. Also initialize the
4596 register information struct. */
4597 for (mcnt = 1; mcnt < num_regs; mcnt++)
4598 regstart[mcnt] = regend[mcnt] = REG_UNSET_VALUE;
4600 /* Shorten strings to `stop'. */
4601 if (stop <= size1)
4603 size1 = stop;
4604 size2 = 0;
4606 else if (stop <= size1 + size2)
4607 size2 = stop - size1;
4609 /* We move `string1' into `string2' if the latter's empty -- but not if
4610 `string1' is null. */
4611 if (size2 == 0 && string1 != NULL)
4613 string2 = string1;
4614 size2 = size1;
4615 string1 = 0;
4616 size1 = 0;
4618 end1 = string1 + size1;
4619 end2 = string2 + size2;
4621 /* Compute where to stop matching, within the two strings. */
4622 end_match_1 = end1;
4623 end_match_2 = end2;
4625 /* `p' scans through the pattern as `d' scans through the data.
4626 `dend' is the end of the input string that `d' points within. `d'
4627 is advanced into the following input string whenever necessary, but
4628 this happens before fetching; therefore, at the beginning of the
4629 loop, `d' can be pointing at the end of a string, but it cannot
4630 equal `string2'. */
4631 if (size1 > 0 && pos <= size1)
4633 d = string1 + pos;
4634 dend = end_match_1;
4636 else
4638 d = string2 + pos - size1;
4639 dend = end_match_2;
4642 DEBUG_PRINT1 ("The compiled pattern is: ");
4643 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4644 DEBUG_PRINT1 ("The string to match is: `");
4645 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4646 DEBUG_PRINT1 ("'\n");
4648 /* This loops over pattern commands. It exits by returning from the
4649 function if the match is complete, or it drops through if the match
4650 fails at this starting point in the input data. */
4651 for (;;)
4653 DEBUG_PRINT2 ("\n%p: ", p);
4655 if (p == pend)
4656 { /* End of pattern means we might have succeeded. */
4657 DEBUG_PRINT1 ("end of pattern ... ");
4659 /* If we haven't matched the entire string, and we want the
4660 longest match, try backtracking. */
4661 if (d != end_match_2)
4663 /* 1 if this match ends in the same string (string1 or string2)
4664 as the best previous match. */
4665 boolean same_str_p = (FIRST_STRING_P (match_end)
4666 == FIRST_STRING_P (d));
4667 /* 1 if this match is the best seen so far. */
4668 boolean best_match_p;
4670 /* AIX compiler got confused when this was combined
4671 with the previous declaration. */
4672 if (same_str_p)
4673 best_match_p = d > match_end;
4674 else
4675 best_match_p = !FIRST_STRING_P (d);
4677 DEBUG_PRINT1 ("backtracking.\n");
4679 if (!FAIL_STACK_EMPTY ())
4680 { /* More failure points to try. */
4682 /* If exceeds best match so far, save it. */
4683 if (!best_regs_set || best_match_p)
4685 best_regs_set = true;
4686 match_end = d;
4688 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4690 for (mcnt = 1; mcnt < num_regs; mcnt++)
4692 best_regstart[mcnt] = regstart[mcnt];
4693 best_regend[mcnt] = regend[mcnt];
4696 goto fail;
4699 /* If no failure points, don't restore garbage. And if
4700 last match is real best match, don't restore second
4701 best one. */
4702 else if (best_regs_set && !best_match_p)
4704 restore_best_regs:
4705 /* Restore best match. It may happen that `dend ==
4706 end_match_1' while the restored d is in string2.
4707 For example, the pattern `x.*y.*z' against the
4708 strings `x-' and `y-z-', if the two strings are
4709 not consecutive in memory. */
4710 DEBUG_PRINT1 ("Restoring best registers.\n");
4712 d = match_end;
4713 dend = ((d >= string1 && d <= end1)
4714 ? end_match_1 : end_match_2);
4716 for (mcnt = 1; mcnt < num_regs; mcnt++)
4718 regstart[mcnt] = best_regstart[mcnt];
4719 regend[mcnt] = best_regend[mcnt];
4722 } /* d != end_match_2 */
4724 succeed_label:
4725 DEBUG_PRINT1 ("Accepting match.\n");
4727 /* If caller wants register contents data back, do it. */
4728 if (regs && !bufp->no_sub)
4730 /* Have the register data arrays been allocated? */
4731 if (bufp->regs_allocated == REGS_UNALLOCATED)
4732 { /* No. So allocate them with malloc. We need one
4733 extra element beyond `num_regs' for the `-1' marker
4734 GNU code uses. */
4735 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4736 regs->start = TALLOC (regs->num_regs, regoff_t);
4737 regs->end = TALLOC (regs->num_regs, regoff_t);
4738 if (regs->start == NULL || regs->end == NULL)
4740 FREE_VARIABLES ();
4741 return -2;
4743 bufp->regs_allocated = REGS_REALLOCATE;
4745 else if (bufp->regs_allocated == REGS_REALLOCATE)
4746 { /* Yes. If we need more elements than were already
4747 allocated, reallocate them. If we need fewer, just
4748 leave it alone. */
4749 if (regs->num_regs < num_regs + 1)
4751 regs->num_regs = num_regs + 1;
4752 RETALLOC (regs->start, regs->num_regs, regoff_t);
4753 RETALLOC (regs->end, regs->num_regs, regoff_t);
4754 if (regs->start == NULL || regs->end == NULL)
4756 FREE_VARIABLES ();
4757 return -2;
4761 else
4763 /* These braces fend off a "empty body in an else-statement"
4764 warning under GCC when assert expands to nothing. */
4765 assert (bufp->regs_allocated == REGS_FIXED);
4768 /* Convert the pointer data in `regstart' and `regend' to
4769 indices. Register zero has to be set differently,
4770 since we haven't kept track of any info for it. */
4771 if (regs->num_regs > 0)
4773 regs->start[0] = pos;
4774 regs->end[0] = POINTER_TO_OFFSET (d);
4777 /* Go through the first `min (num_regs, regs->num_regs)'
4778 registers, since that is all we initialized. */
4779 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4781 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4782 regs->start[mcnt] = regs->end[mcnt] = -1;
4783 else
4785 regs->start[mcnt]
4786 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4787 regs->end[mcnt]
4788 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4792 /* If the regs structure we return has more elements than
4793 were in the pattern, set the extra elements to -1. If
4794 we (re)allocated the registers, this is the case,
4795 because we always allocate enough to have at least one
4796 -1 at the end. */
4797 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4798 regs->start[mcnt] = regs->end[mcnt] = -1;
4799 } /* regs && !bufp->no_sub */
4801 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4802 nfailure_points_pushed, nfailure_points_popped,
4803 nfailure_points_pushed - nfailure_points_popped);
4804 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4806 mcnt = POINTER_TO_OFFSET (d) - pos;
4808 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4810 FREE_VARIABLES ();
4811 return mcnt;
4814 /* Otherwise match next pattern command. */
4815 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4817 /* Ignore these. Used to ignore the n of succeed_n's which
4818 currently have n == 0. */
4819 case no_op:
4820 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4821 break;
4823 case succeed:
4824 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4825 goto succeed_label;
4827 /* Match the next n pattern characters exactly. The following
4828 byte in the pattern defines n, and the n bytes after that
4829 are the characters to match. */
4830 case exactn:
4831 mcnt = *p++;
4832 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4834 /* Remember the start point to rollback upon failure. */
4835 dfail = d;
4837 /* This is written out as an if-else so we don't waste time
4838 testing `translate' inside the loop. */
4839 if (RE_TRANSLATE_P (translate))
4841 #ifdef emacs
4842 if (multibyte)
4845 int pat_charlen, buf_charlen;
4846 unsigned int pat_ch, buf_ch;
4848 PREFETCH ();
4849 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4850 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4852 if (RE_TRANSLATE (translate, buf_ch)
4853 != pat_ch)
4855 d = dfail;
4856 goto fail;
4859 p += pat_charlen;
4860 d += buf_charlen;
4861 mcnt -= pat_charlen;
4863 while (mcnt > 0);
4864 else
4865 #endif /* not emacs */
4868 PREFETCH ();
4869 if (RE_TRANSLATE (translate, *d) != *p++)
4871 d = dfail;
4872 goto fail;
4874 d++;
4876 while (--mcnt);
4878 else
4882 PREFETCH ();
4883 if (*d++ != *p++)
4885 d = dfail;
4886 goto fail;
4889 while (--mcnt);
4891 break;
4894 /* Match any character except possibly a newline or a null. */
4895 case anychar:
4897 int buf_charlen;
4898 unsigned int buf_ch;
4900 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4902 PREFETCH ();
4904 #ifdef emacs
4905 if (multibyte)
4906 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4907 else
4908 #endif /* not emacs */
4910 buf_ch = *d;
4911 buf_charlen = 1;
4914 buf_ch = TRANSLATE (buf_ch);
4916 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4917 && buf_ch == '\n')
4918 || ((bufp->syntax & RE_DOT_NOT_NULL)
4919 && buf_ch == '\000'))
4920 goto fail;
4922 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4923 d += buf_charlen;
4925 break;
4928 case charset:
4929 case charset_not:
4931 register unsigned int c;
4932 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4933 int len;
4935 /* Start of actual range_table, or end of bitmap if there is no
4936 range table. */
4937 unsigned char *range_table;
4939 /* Nonzero if there is a range table. */
4940 int range_table_exists;
4942 /* Number of ranges of range table. This is not included
4943 in the initial byte-length of the command. */
4944 int count = 0;
4946 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4948 PREFETCH ();
4949 c = *d;
4951 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4953 #ifdef emacs
4954 if (range_table_exists)
4956 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4957 EXTRACT_NUMBER_AND_INCR (count, range_table);
4960 if (multibyte && BASE_LEADING_CODE_P (c))
4961 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4962 #endif /* emacs */
4964 if (SINGLE_BYTE_CHAR_P (c))
4965 { /* Lookup bitmap. */
4966 c = TRANSLATE (c); /* The character to match. */
4967 len = 1;
4969 /* Cast to `unsigned' instead of `unsigned char' in
4970 case the bit list is a full 32 bytes long. */
4971 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4972 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4973 not = !not;
4975 #ifdef emacs
4976 else if (range_table_exists)
4978 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
4980 if ( (class_bits & BIT_ALNUM && ISALNUM (c))
4981 | (class_bits & BIT_ALPHA && ISALPHA (c))
4982 | (class_bits & BIT_ASCII && IS_REAL_ASCII (c))
4983 | (class_bits & BIT_GRAPH && ISGRAPH (c))
4984 | (class_bits & BIT_LOWER && ISLOWER (c))
4985 | (class_bits & BIT_MULTIBYTE && !ISUNIBYTE (c))
4986 | (class_bits & BIT_NONASCII && !IS_REAL_ASCII (c))
4987 | (class_bits & BIT_PRINT && ISPRINT (c))
4988 | (class_bits & BIT_PUNCT && ISPUNCT (c))
4989 | (class_bits & BIT_SPACE && ISSPACE (c))
4990 | (class_bits & BIT_UNIBYTE && ISUNIBYTE (c))
4991 | (class_bits & BIT_UPPER && ISUPPER (c))
4992 | (class_bits & BIT_WORD && ISWORD (c)))
4993 not = !not;
4994 else
4995 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4997 #endif /* emacs */
4999 if (range_table_exists)
5000 p = CHARSET_RANGE_TABLE_END (range_table, count);
5001 else
5002 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5004 if (!not) goto fail;
5006 d += len;
5007 break;
5011 /* The beginning of a group is represented by start_memory.
5012 The argument is the register number. The text
5013 matched within the group is recorded (in the internal
5014 registers data structure) under the register number. */
5015 case start_memory:
5016 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5018 /* In case we need to undo this operation (via backtracking). */
5019 PUSH_FAILURE_REG ((unsigned int)*p);
5021 regstart[*p] = d;
5022 regend[*p] = REG_UNSET_VALUE; /* probably unnecessary. -sm */
5023 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5025 /* Move past the register number and inner group count. */
5026 p += 1;
5027 break;
5030 /* The stop_memory opcode represents the end of a group. Its
5031 argument is the same as start_memory's: the register number. */
5032 case stop_memory:
5033 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5035 assert (!REG_UNSET (regstart[*p]));
5036 /* Strictly speaking, there should be code such as:
5038 assert (REG_UNSET (regend[*p]));
5039 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5041 But the only info to be pushed is regend[*p] and it is known to
5042 be UNSET, so there really isn't anything to push.
5043 Not pushing anything, on the other hand deprives us from the
5044 guarantee that regend[*p] is UNSET since undoing this operation
5045 will not reset its value properly. This is not important since
5046 the value will only be read on the next start_memory or at
5047 the very end and both events can only happen if this stop_memory
5048 is *not* undone. */
5050 regend[*p] = d;
5051 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5053 /* Move past the register number and the inner group count. */
5054 p += 1;
5055 break;
5058 /* \<digit> has been turned into a `duplicate' command which is
5059 followed by the numeric value of <digit> as the register number. */
5060 case duplicate:
5062 register re_char *d2, *dend2;
5063 int regno = *p++; /* Get which register to match against. */
5064 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5066 /* Can't back reference a group which we've never matched. */
5067 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5068 goto fail;
5070 /* Where in input to try to start matching. */
5071 d2 = regstart[regno];
5073 /* Remember the start point to rollback upon failure. */
5074 dfail = d;
5076 /* Where to stop matching; if both the place to start and
5077 the place to stop matching are in the same string, then
5078 set to the place to stop, otherwise, for now have to use
5079 the end of the first string. */
5081 dend2 = ((FIRST_STRING_P (regstart[regno])
5082 == FIRST_STRING_P (regend[regno]))
5083 ? regend[regno] : end_match_1);
5084 for (;;)
5086 /* If necessary, advance to next segment in register
5087 contents. */
5088 while (d2 == dend2)
5090 if (dend2 == end_match_2) break;
5091 if (dend2 == regend[regno]) break;
5093 /* End of string1 => advance to string2. */
5094 d2 = string2;
5095 dend2 = regend[regno];
5097 /* At end of register contents => success */
5098 if (d2 == dend2) break;
5100 /* If necessary, advance to next segment in data. */
5101 PREFETCH ();
5103 /* How many characters left in this segment to match. */
5104 mcnt = dend - d;
5106 /* Want how many consecutive characters we can match in
5107 one shot, so, if necessary, adjust the count. */
5108 if (mcnt > dend2 - d2)
5109 mcnt = dend2 - d2;
5111 /* Compare that many; failure if mismatch, else move
5112 past them. */
5113 if (RE_TRANSLATE_P (translate)
5114 ? bcmp_translate (d, d2, mcnt, translate)
5115 : bcmp (d, d2, mcnt))
5117 d = dfail;
5118 goto fail;
5120 d += mcnt, d2 += mcnt;
5123 break;
5126 /* begline matches the empty string at the beginning of the string
5127 (unless `not_bol' is set in `bufp'), and, if
5128 `newline_anchor' is set, after newlines. */
5129 case begline:
5130 DEBUG_PRINT1 ("EXECUTING begline.\n");
5132 if (AT_STRINGS_BEG (d))
5134 if (!bufp->not_bol) break;
5136 else if (d[-1] == '\n' && bufp->newline_anchor)
5138 break;
5140 /* In all other cases, we fail. */
5141 goto fail;
5144 /* endline is the dual of begline. */
5145 case endline:
5146 DEBUG_PRINT1 ("EXECUTING endline.\n");
5148 if (AT_STRINGS_END (d))
5150 if (!bufp->not_eol) break;
5153 /* We have to ``prefetch'' the next character. */
5154 else if ((d == end1 ? *string2 : *d) == '\n'
5155 && bufp->newline_anchor)
5157 break;
5159 goto fail;
5162 /* Match at the very beginning of the data. */
5163 case begbuf:
5164 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5165 if (AT_STRINGS_BEG (d))
5166 break;
5167 goto fail;
5170 /* Match at the very end of the data. */
5171 case endbuf:
5172 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5173 if (AT_STRINGS_END (d))
5174 break;
5175 goto fail;
5178 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5179 pushes NULL as the value for the string on the stack. Then
5180 `POP_FAILURE_POINT' will keep the current value for the
5181 string, instead of restoring it. To see why, consider
5182 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5183 then the . fails against the \n. But the next thing we want
5184 to do is match the \n against the \n; if we restored the
5185 string value, we would be back at the foo.
5187 Because this is used only in specific cases, we don't need to
5188 check all the things that `on_failure_jump' does, to make
5189 sure the right things get saved on the stack. Hence we don't
5190 share its code. The only reason to push anything on the
5191 stack at all is that otherwise we would have to change
5192 `anychar's code to do something besides goto fail in this
5193 case; that seems worse than this. */
5194 case on_failure_keep_string_jump:
5195 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5196 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5197 mcnt, p + mcnt);
5199 PUSH_FAILURE_POINT (p - 3, NULL);
5200 break;
5203 /* Simple loop detecting on_failure_jump: just check on the
5204 failure stack if the same spot was already hit earlier. */
5205 case on_failure_jump_loop:
5206 on_failure:
5207 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5208 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5209 mcnt, p + mcnt);
5211 CHECK_INFINITE_LOOP (p - 3, d);
5212 PUSH_FAILURE_POINT (p - 3, d);
5213 break;
5216 /* Uses of on_failure_jump:
5218 Each alternative starts with an on_failure_jump that points
5219 to the beginning of the next alternative. Each alternative
5220 except the last ends with a jump that in effect jumps past
5221 the rest of the alternatives. (They really jump to the
5222 ending jump of the following alternative, because tensioning
5223 these jumps is a hassle.)
5225 Repeats start with an on_failure_jump that points past both
5226 the repetition text and either the following jump or
5227 pop_failure_jump back to this on_failure_jump. */
5228 case on_failure_jump:
5229 QUIT;
5230 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5231 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5232 mcnt, p + mcnt);
5234 PUSH_FAILURE_POINT (p -3, d);
5235 break;
5237 /* This operation is used for greedy *.
5238 Compare the beginning of the repeat with what in the
5239 pattern follows its end. If we can establish that there
5240 is nothing that they would both match, i.e., that we
5241 would have to backtrack because of (as in, e.g., `a*a')
5242 then we can use a non-backtracking loop based on
5243 on_failure_keep_string_jump instead of on_failure_jump. */
5244 case on_failure_jump_smart:
5245 QUIT;
5246 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5247 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5248 mcnt, p + mcnt);
5250 unsigned char *p1 = p; /* Next operation. */
5251 unsigned char *p2 = p + mcnt; /* Destination of the jump. */
5253 p -= 3; /* Reset so that we will re-execute the
5254 instruction once it's been changed. */
5256 EXTRACT_NUMBER (mcnt, p2 - 2);
5258 /* Ensure this is a indeed the trivial kind of loop
5259 we are expecting. */
5260 assert (skip_one_char (p1) == p2 - 3);
5261 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5262 DEBUG_STATEMENT (debug += 2);
5263 if (mutually_exclusive_p (bufp, p1, p2))
5265 /* Use a fast `on_failure_keep_string_jump' loop. */
5266 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5267 *p = (unsigned char) on_failure_keep_string_jump;
5268 STORE_NUMBER (p2 - 2, mcnt + 3);
5270 else
5272 /* Default to a safe `on_failure_jump' loop. */
5273 DEBUG_PRINT1 (" smart default => slow loop.\n");
5274 *p = (unsigned char) on_failure_jump;
5276 DEBUG_STATEMENT (debug -= 2);
5278 break;
5280 /* Unconditionally jump (without popping any failure points). */
5281 case jump:
5282 unconditional_jump:
5283 QUIT;
5284 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5285 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5286 p += mcnt; /* Do the jump. */
5287 DEBUG_PRINT2 ("(to %p).\n", p);
5288 break;
5291 /* Have to succeed matching what follows at least n times.
5292 After that, handle like `on_failure_jump'. */
5293 case succeed_n:
5294 EXTRACT_NUMBER (mcnt, p + 2);
5295 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5297 assert (mcnt >= 0);
5298 /* Originally, this is how many times we HAVE to succeed. */
5299 if (mcnt > 0)
5301 mcnt--;
5302 p += 2;
5303 STORE_NUMBER_AND_INCR (p, mcnt);
5304 DEBUG_PRINT3 (" Setting %p to %d.\n", p, mcnt);
5306 else if (mcnt == 0)
5308 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
5309 p[2] = (unsigned char) no_op;
5310 p[3] = (unsigned char) no_op;
5311 goto on_failure;
5313 break;
5315 case jump_n:
5316 EXTRACT_NUMBER (mcnt, p + 2);
5317 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5319 /* Originally, this is how many times we CAN jump. */
5320 if (mcnt)
5322 mcnt--;
5323 STORE_NUMBER (p + 2, mcnt);
5324 goto unconditional_jump;
5326 /* If don't have to jump any more, skip over the rest of command. */
5327 else
5328 p += 4;
5329 break;
5331 case set_number_at:
5333 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5335 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5336 p1 = p + mcnt;
5337 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5338 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
5339 STORE_NUMBER (p1, mcnt);
5340 break;
5343 case wordbound:
5344 case notwordbound:
5345 not = (re_opcode_t) *(p - 1) == notwordbound;
5346 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5348 /* We SUCCEED (or FAIL) in one of the following cases: */
5350 /* Case 1: D is at the beginning or the end of string. */
5351 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5352 not = !not;
5353 else
5355 /* C1 is the character before D, S1 is the syntax of C1, C2
5356 is the character at D, and S2 is the syntax of C2. */
5357 int c1, c2, s1, s2;
5358 #ifdef emacs
5359 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d - 1));
5360 UPDATE_SYNTAX_TABLE (charpos);
5361 #endif
5362 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5363 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5364 s1 = SYNTAX (c1);
5365 #ifdef emacs
5366 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5367 #endif
5368 PREFETCH ();
5369 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5370 c2 = STRING_CHAR (d, dend - d);
5371 s2 = SYNTAX (c2);
5373 if (/* Case 2: Only one of S1 and S2 is Sword. */
5374 ((s1 == Sword) != (s2 == Sword))
5375 /* Case 3: Both of S1 and S2 are Sword, and macro
5376 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5377 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5378 not = !not;
5380 if (not)
5381 break;
5382 else
5383 goto fail;
5385 case wordbeg:
5386 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5388 /* We FAIL in one of the following cases: */
5390 /* Case 1: D is at the end of string. */
5391 if (AT_STRINGS_END (d))
5392 goto fail;
5393 else
5395 /* C1 is the character before D, S1 is the syntax of C1, C2
5396 is the character at D, and S2 is the syntax of C2. */
5397 int c1, c2, s1, s2;
5398 #ifdef emacs
5399 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5400 UPDATE_SYNTAX_TABLE (charpos);
5401 #endif
5402 PREFETCH ();
5403 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5404 c2 = STRING_CHAR (d, dend - d);
5405 s2 = SYNTAX (c2);
5407 /* Case 2: S2 is not Sword. */
5408 if (s2 != Sword)
5409 goto fail;
5411 /* Case 3: D is not at the beginning of string ... */
5412 if (!AT_STRINGS_BEG (d))
5414 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5415 #ifdef emacs
5416 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5417 #endif
5418 s1 = SYNTAX (c1);
5420 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5421 returns 0. */
5422 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5423 goto fail;
5426 break;
5428 case wordend:
5429 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5431 /* We FAIL in one of the following cases: */
5433 /* Case 1: D is at the beginning of string. */
5434 if (AT_STRINGS_BEG (d))
5435 goto fail;
5436 else
5438 /* C1 is the character before D, S1 is the syntax of C1, C2
5439 is the character at D, and S2 is the syntax of C2. */
5440 int c1, c2, s1, s2;
5441 #ifdef emacs
5442 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d) - 1);
5443 UPDATE_SYNTAX_TABLE (charpos);
5444 #endif
5445 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5446 s1 = SYNTAX (c1);
5448 /* Case 2: S1 is not Sword. */
5449 if (s1 != Sword)
5450 goto fail;
5452 /* Case 3: D is not at the end of string ... */
5453 if (!AT_STRINGS_END (d))
5455 PREFETCH ();
5456 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5457 c2 = STRING_CHAR (d, dend - d);
5458 #ifdef emacs
5459 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5460 #endif
5461 s2 = SYNTAX (c2);
5463 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5464 returns 0. */
5465 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5466 goto fail;
5469 break;
5471 #ifdef emacs
5472 case before_dot:
5473 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5474 if (PTR_BYTE_POS (d) >= PT_BYTE)
5475 goto fail;
5476 break;
5478 case at_dot:
5479 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5480 if (PTR_BYTE_POS (d) != PT_BYTE)
5481 goto fail;
5482 break;
5484 case after_dot:
5485 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5486 if (PTR_BYTE_POS (d) <= PT_BYTE)
5487 goto fail;
5488 break;
5490 case syntaxspec:
5491 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
5492 mcnt = *p++;
5493 goto matchsyntax;
5495 case wordchar:
5496 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5497 mcnt = (int) Sword;
5498 matchsyntax:
5499 PREFETCH ();
5500 #ifdef emacs
5502 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5503 UPDATE_SYNTAX_TABLE (pos1);
5505 #endif
5507 int c, len;
5509 if (multibyte)
5510 /* we must concern about multibyte form, ... */
5511 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5512 else
5513 /* everything should be handled as ASCII, even though it
5514 looks like multibyte form. */
5515 c = *d, len = 1;
5517 if (SYNTAX (c) != (enum syntaxcode) mcnt)
5518 goto fail;
5519 d += len;
5521 break;
5523 case notsyntaxspec:
5524 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
5525 mcnt = *p++;
5526 goto matchnotsyntax;
5528 case notwordchar:
5529 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5530 mcnt = (int) Sword;
5531 matchnotsyntax:
5532 PREFETCH ();
5533 #ifdef emacs
5535 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5536 UPDATE_SYNTAX_TABLE (pos1);
5538 #endif
5540 int c, len;
5542 if (multibyte)
5543 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5544 else
5545 c = *d, len = 1;
5547 if (SYNTAX (c) == (enum syntaxcode) mcnt)
5548 goto fail;
5549 d += len;
5551 break;
5553 case categoryspec:
5554 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p);
5555 mcnt = *p++;
5556 PREFETCH ();
5558 int c, len;
5560 if (multibyte)
5561 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5562 else
5563 c = *d, len = 1;
5565 if (!CHAR_HAS_CATEGORY (c, mcnt))
5566 goto fail;
5567 d += len;
5569 break;
5571 case notcategoryspec:
5572 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p);
5573 mcnt = *p++;
5574 PREFETCH ();
5576 int c, len;
5578 if (multibyte)
5579 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5580 else
5581 c = *d, len = 1;
5583 if (CHAR_HAS_CATEGORY (c, mcnt))
5584 goto fail;
5585 d += len;
5587 break;
5589 #else /* not emacs */
5590 case wordchar:
5591 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5592 PREFETCH ();
5593 if (!WORDCHAR_P (d))
5594 goto fail;
5595 d++;
5596 break;
5598 case notwordchar:
5599 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5600 PREFETCH ();
5601 if (WORDCHAR_P (d))
5602 goto fail;
5603 d++;
5604 break;
5605 #endif /* not emacs */
5607 default:
5608 abort ();
5610 continue; /* Successfully executed one pattern command; keep going. */
5613 /* We goto here if a matching operation fails. */
5614 fail:
5615 QUIT;
5616 if (!FAIL_STACK_EMPTY ())
5618 re_char *str;
5619 unsigned char *pat;
5620 /* A restart point is known. Restore to that state. */
5621 DEBUG_PRINT1 ("\nFAIL:\n");
5622 POP_FAILURE_POINT (str, pat);
5623 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5625 case on_failure_keep_string_jump:
5626 assert (str == NULL);
5627 goto continue_failure_jump;
5629 case on_failure_jump_loop:
5630 case on_failure_jump:
5631 case succeed_n:
5632 d = str;
5633 continue_failure_jump:
5634 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5635 p = pat + mcnt;
5636 break;
5638 default:
5639 abort();
5642 assert (p >= bufp->buffer && p <= pend);
5644 if (d >= string1 && d <= end1)
5645 dend = end_match_1;
5647 else
5648 break; /* Matching at this starting point really fails. */
5649 } /* for (;;) */
5651 if (best_regs_set)
5652 goto restore_best_regs;
5654 FREE_VARIABLES ();
5656 return -1; /* Failure to match. */
5657 } /* re_match_2 */
5659 /* Subroutine definitions for re_match_2. */
5661 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5662 bytes; nonzero otherwise. */
5664 static int
5665 bcmp_translate (s1, s2, len, translate)
5666 unsigned char *s1, *s2;
5667 register int len;
5668 RE_TRANSLATE_TYPE translate;
5670 register unsigned char *p1 = s1, *p2 = s2;
5671 unsigned char *p1_end = s1 + len;
5672 unsigned char *p2_end = s2 + len;
5674 while (p1 != p1_end && p2 != p2_end)
5676 int p1_charlen, p2_charlen;
5677 int p1_ch, p2_ch;
5679 /* FIXME: This assumes `multibyte = true'. */
5680 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5681 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5683 if (RE_TRANSLATE (translate, p1_ch)
5684 != RE_TRANSLATE (translate, p2_ch))
5685 return 1;
5687 p1 += p1_charlen, p2 += p2_charlen;
5690 if (p1 != p1_end || p2 != p2_end)
5691 return 1;
5693 return 0;
5696 /* Entry points for GNU code. */
5698 /* re_compile_pattern is the GNU regular expression compiler: it
5699 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5700 Returns 0 if the pattern was valid, otherwise an error string.
5702 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5703 are set in BUFP on entry.
5705 We call regex_compile to do the actual compilation. */
5707 const char *
5708 re_compile_pattern (pattern, length, bufp)
5709 const char *pattern;
5710 int length;
5711 struct re_pattern_buffer *bufp;
5713 reg_errcode_t ret;
5715 /* GNU code is written to assume at least RE_NREGS registers will be set
5716 (and at least one extra will be -1). */
5717 bufp->regs_allocated = REGS_UNALLOCATED;
5719 /* And GNU code determines whether or not to get register information
5720 by passing null for the REGS argument to re_match, etc., not by
5721 setting no_sub. */
5722 bufp->no_sub = 0;
5724 /* Match anchors at newline. */
5725 bufp->newline_anchor = 1;
5727 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5729 if (!ret)
5730 return NULL;
5731 return gettext (re_error_msgid[(int) ret]);
5734 /* Entry points compatible with 4.2 BSD regex library. We don't define
5735 them unless specifically requested. */
5737 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5739 /* BSD has one and only one pattern buffer. */
5740 static struct re_pattern_buffer re_comp_buf;
5742 char *
5743 #ifdef _LIBC
5744 /* Make these definitions weak in libc, so POSIX programs can redefine
5745 these names if they don't use our functions, and still use
5746 regcomp/regexec below without link errors. */
5747 weak_function
5748 #endif
5749 re_comp (s)
5750 const char *s;
5752 reg_errcode_t ret;
5754 if (!s)
5756 if (!re_comp_buf.buffer)
5757 return gettext ("No previous regular expression");
5758 return 0;
5761 if (!re_comp_buf.buffer)
5763 re_comp_buf.buffer = (unsigned char *) malloc (200);
5764 if (re_comp_buf.buffer == NULL)
5765 return gettext (re_error_msgid[(int) REG_ESPACE]);
5766 re_comp_buf.allocated = 200;
5768 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5769 if (re_comp_buf.fastmap == NULL)
5770 return gettext (re_error_msgid[(int) REG_ESPACE]);
5773 /* Since `re_exec' always passes NULL for the `regs' argument, we
5774 don't need to initialize the pattern buffer fields which affect it. */
5776 /* Match anchors at newlines. */
5777 re_comp_buf.newline_anchor = 1;
5779 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5781 if (!ret)
5782 return NULL;
5784 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5785 return (char *) gettext (re_error_msgid[(int) ret]);
5790 #ifdef _LIBC
5791 weak_function
5792 #endif
5793 re_exec (s)
5794 const char *s;
5796 const int len = strlen (s);
5797 return
5798 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5800 #endif /* _REGEX_RE_COMP */
5802 /* POSIX.2 functions. Don't define these for Emacs. */
5804 #ifndef emacs
5806 /* regcomp takes a regular expression as a string and compiles it.
5808 PREG is a regex_t *. We do not expect any fields to be initialized,
5809 since POSIX says we shouldn't. Thus, we set
5811 `buffer' to the compiled pattern;
5812 `used' to the length of the compiled pattern;
5813 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5814 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5815 RE_SYNTAX_POSIX_BASIC;
5816 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5817 `fastmap' and `fastmap_accurate' to zero;
5818 `re_nsub' to the number of subexpressions in PATTERN.
5820 PATTERN is the address of the pattern string.
5822 CFLAGS is a series of bits which affect compilation.
5824 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5825 use POSIX basic syntax.
5827 If REG_NEWLINE is set, then . and [^...] don't match newline.
5828 Also, regexec will try a match beginning after every newline.
5830 If REG_ICASE is set, then we considers upper- and lowercase
5831 versions of letters to be equivalent when matching.
5833 If REG_NOSUB is set, then when PREG is passed to regexec, that
5834 routine will report only success or failure, and nothing about the
5835 registers.
5837 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5838 the return codes and their meanings.) */
5841 regcomp (preg, pattern, cflags)
5842 regex_t *preg;
5843 const char *pattern;
5844 int cflags;
5846 reg_errcode_t ret;
5847 unsigned syntax
5848 = (cflags & REG_EXTENDED) ?
5849 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5851 /* regex_compile will allocate the space for the compiled pattern. */
5852 preg->buffer = 0;
5853 preg->allocated = 0;
5854 preg->used = 0;
5856 /* Don't bother to use a fastmap when searching. This simplifies the
5857 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5858 characters after newlines into the fastmap. This way, we just try
5859 every character. */
5860 preg->fastmap = 0;
5862 if (cflags & REG_ICASE)
5864 unsigned i;
5866 preg->translate
5867 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5868 * sizeof (*(RE_TRANSLATE_TYPE)0));
5869 if (preg->translate == NULL)
5870 return (int) REG_ESPACE;
5872 /* Map uppercase characters to corresponding lowercase ones. */
5873 for (i = 0; i < CHAR_SET_SIZE; i++)
5874 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5876 else
5877 preg->translate = NULL;
5879 /* If REG_NEWLINE is set, newlines are treated differently. */
5880 if (cflags & REG_NEWLINE)
5881 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5882 syntax &= ~RE_DOT_NEWLINE;
5883 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5884 /* It also changes the matching behavior. */
5885 preg->newline_anchor = 1;
5887 else
5888 preg->newline_anchor = 0;
5890 preg->no_sub = !!(cflags & REG_NOSUB);
5892 /* POSIX says a null character in the pattern terminates it, so we
5893 can use strlen here in compiling the pattern. */
5894 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5896 /* POSIX doesn't distinguish between an unmatched open-group and an
5897 unmatched close-group: both are REG_EPAREN. */
5898 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5900 return (int) ret;
5904 /* regexec searches for a given pattern, specified by PREG, in the
5905 string STRING.
5907 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5908 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5909 least NMATCH elements, and we set them to the offsets of the
5910 corresponding matched substrings.
5912 EFLAGS specifies `execution flags' which affect matching: if
5913 REG_NOTBOL is set, then ^ does not match at the beginning of the
5914 string; if REG_NOTEOL is set, then $ does not match at the end.
5916 We return 0 if we find a match and REG_NOMATCH if not. */
5919 regexec (preg, string, nmatch, pmatch, eflags)
5920 const regex_t *preg;
5921 const char *string;
5922 size_t nmatch;
5923 regmatch_t pmatch[];
5924 int eflags;
5926 int ret;
5927 struct re_registers regs;
5928 regex_t private_preg;
5929 int len = strlen (string);
5930 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5932 private_preg = *preg;
5934 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5935 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5937 /* The user has told us exactly how many registers to return
5938 information about, via `nmatch'. We have to pass that on to the
5939 matching routines. */
5940 private_preg.regs_allocated = REGS_FIXED;
5942 if (want_reg_info)
5944 regs.num_regs = nmatch;
5945 regs.start = TALLOC (nmatch, regoff_t);
5946 regs.end = TALLOC (nmatch, regoff_t);
5947 if (regs.start == NULL || regs.end == NULL)
5948 return (int) REG_NOMATCH;
5951 /* Perform the searching operation. */
5952 ret = re_search (&private_preg, string, len,
5953 /* start: */ 0, /* range: */ len,
5954 want_reg_info ? &regs : (struct re_registers *) 0);
5956 /* Copy the register information to the POSIX structure. */
5957 if (want_reg_info)
5959 if (ret >= 0)
5961 unsigned r;
5963 for (r = 0; r < nmatch; r++)
5965 pmatch[r].rm_so = regs.start[r];
5966 pmatch[r].rm_eo = regs.end[r];
5970 /* If we needed the temporary register info, free the space now. */
5971 free (regs.start);
5972 free (regs.end);
5975 /* We want zero return to mean success, unlike `re_search'. */
5976 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5980 /* Returns a message corresponding to an error code, ERRCODE, returned
5981 from either regcomp or regexec. We don't use PREG here. */
5983 size_t
5984 regerror (errcode, preg, errbuf, errbuf_size)
5985 int errcode;
5986 const regex_t *preg;
5987 char *errbuf;
5988 size_t errbuf_size;
5990 const char *msg;
5991 size_t msg_size;
5993 if (errcode < 0
5994 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
5995 /* Only error codes returned by the rest of the code should be passed
5996 to this routine. If we are given anything else, or if other regex
5997 code generates an invalid error code, then the program has a bug.
5998 Dump core so we can fix it. */
5999 abort ();
6001 msg = gettext (re_error_msgid[errcode]);
6003 msg_size = strlen (msg) + 1; /* Includes the null. */
6005 if (errbuf_size != 0)
6007 if (msg_size > errbuf_size)
6009 strncpy (errbuf, msg, errbuf_size - 1);
6010 errbuf[errbuf_size - 1] = 0;
6012 else
6013 strcpy (errbuf, msg);
6016 return msg_size;
6020 /* Free dynamically allocated space used by PREG. */
6022 void
6023 regfree (preg)
6024 regex_t *preg;
6026 if (preg->buffer != NULL)
6027 free (preg->buffer);
6028 preg->buffer = NULL;
6030 preg->allocated = 0;
6031 preg->used = 0;
6033 if (preg->fastmap != NULL)
6034 free (preg->fastmap);
6035 preg->fastmap = NULL;
6036 preg->fastmap_accurate = 0;
6038 if (preg->translate != NULL)
6039 free (preg->translate);
6040 preg->translate = NULL;
6043 #endif /* not emacs */