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)
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,
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)
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)))
43 #define PTR_TO_OFFSET(d) 0
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)
57 # define gettext(msgid) (msgid)
61 /* This define is so xgettext can find the internationalizable
63 #define gettext_noop(String) String
66 /* The `emacs' switch turns on certain matching commands
67 that make sense only in Emacs. */
73 /* Make syntax table lookup grant data in gl_state. */
74 #define SYNTAX_ENTRY_VIA_PROPERTY
80 #define malloc xmalloc
81 #define realloc xrealloc
84 #define RE_STRING_CHAR(p, s) \
85 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
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. */
94 #if defined (STDC_HEADERS) || defined (_LIBC)
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
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)
118 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
121 #define bcopy(s, d, n) memcpy ((d), (s), (n))
124 #define bzero(s, n) memset ((s), 0, (n))
131 /* Define the syntax stuff for \<, \>, etc. */
133 /* This must be nonzero for the wordchar and notwordchar pattern
134 commands in re_match_2. */
139 #ifdef SWITCH_ENUM_BUG
140 #define SWITCH_ENUM_CAST(x) ((int)(x))
142 #define SWITCH_ENUM_CAST(x) (x)
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
];
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
;
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 */
200 #define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
201 #define RE_TRANSLATE_P(TBL) (TBL)
204 /* Get the interface, including the syntax bits. */
207 /* isalpha etc. are used for the character classes. */
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) \
236 #define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
237 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
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))
282 #define ISASCII(c) isascii(c)
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))
296 #define ISBLANK(c) (ISASCII (c) && isblank (c))
298 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
301 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
303 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
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 */
322 #define NULL (void *)0
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
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)
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. */
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. */
358 /* Make alloca work the best possible way. */
360 #define alloca __builtin_alloca
361 #else /* not __GNUC__ */
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. */
368 #endif /* not _AIX */
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), \
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 */
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
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))
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
;
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. */
460 /* Succeed right away--no more backtracking. */
463 /* Followed by one byte giving n, then by n literal bytes. */
466 /* Matches any (more or less) character. */
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. */
485 /* Same parameters as charset, but match any character that is
486 not one of those specified. */
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
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
501 /* Match a duplicate of something remembered. Followed by one
502 byte containing the register number. */
505 /* Fail unless at beginning of line. */
508 /* Fail unless at end of line. */
511 /* Succeeds if at beginning of buffer (if emacs) or at beginning
512 of string to be matched (if not). */
515 /* Analogously, for end of buffer/string. */
518 /* Followed by two byte relative address to which to jump. */
521 /* Followed by two-byte relative address of place to resume at
522 in case of failure. */
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
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. */
546 /* Followed by two-byte relative address, and two-byte number n.
547 Jump to the address N times, then fail. */
550 /* Set the following two-byte relative address to the
551 subsequent two-byte number. The address *includes* the two
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. */
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. */
573 /* Matches any character whose syntax is not that specified. */
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). */
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). */
588 /* Common operations on the compiled pattern. */
590 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
592 #define STORE_NUMBER(destination, number) \
594 (destination)[0] = (number) & 0377; \
595 (destination)[1] = (number) >> 8; \
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) \
604 STORE_NUMBER (destination, number); \
605 (destination) += 2; \
608 /* Put into DESTINATION a number stored in two contiguous bytes starting
611 #define EXTRACT_NUMBER(destination, source) \
613 (destination) = *(source) & 0377; \
614 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
619 extract_number (dest
, source
)
621 unsigned char *source
;
623 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
624 *dest
= *source
& 0377;
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 */
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) \
640 EXTRACT_NUMBER (destination, source); \
646 extract_number_and_incr (destination
, source
)
648 unsigned char **source
;
650 extract_number (destination
, *source
);
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 */
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) \
668 (destination)[0] = (character) & 0377; \
669 (destination)[1] = ((character) >> 8) & 0377; \
670 (destination)[2] = (character) >> 16; \
671 (destination) += 3; \
674 /* Put into DESTINATION a character stored in three contiguous bytes
675 starting at SOURCE. */
677 #define EXTRACT_CHARACTER(destination, source) \
679 (destination) = ((source)[0] \
680 | ((source)[1] << 8) \
681 | ((source)[2] << 16)); \
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
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) \
722 int range_start, range_end; \
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) \
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) \
746 /* Number of ranges in range table. */ \
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); \
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. */
763 /* We use standard I/O for debugging. */
766 /* It is useful to test things that ``must'' be true when debugging. */
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. */
785 print_fastmap (fastmap
)
788 unsigned was_a_range
= 0;
791 while (i
< (1 << BYTEWIDTH
))
797 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
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. */
817 print_partial_compiled_pattern (start
, end
)
818 unsigned char *start
;
822 unsigned char *p
= start
;
823 unsigned char *pend
= end
;
831 /* Loop over pattern commands. */
834 printf ("%d:\t", p
- start
);
836 switch ((re_opcode_t
) *p
++)
848 printf ("/exactn/%d", mcnt
);
858 printf ("/start_memory/%d", *p
++);
862 printf ("/stop_memory/%d", *p
++);
866 printf ("/duplicate/%d", *p
++);
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
++)
888 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
890 /* Are we starting a range? */
891 if (last
+ 1 == c
&& ! in_range
)
896 /* Have we broken a range? */
897 else if (last
+ 1 != c
&& in_range
)
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
);
937 case on_failure_jump
:
938 extract_number_and_incr (&mcnt
, &p
);
939 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
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
);
947 case on_failure_jump_loop
:
948 extract_number_and_incr (&mcnt
, &p
);
949 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
952 case on_failure_jump_smart
:
953 extract_number_and_incr (&mcnt
, &p
);
954 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
958 extract_number_and_incr (&mcnt
, &p
);
959 printf ("/jump to %d", p
+ mcnt
- start
);
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
);
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
);
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
);
981 printf ("/wordbound");
985 printf ("/notwordbound");
997 printf ("/before_dot");
1005 printf ("/after_dot");
1009 printf ("/syntaxspec");
1011 printf ("/%d", mcnt
);
1015 printf ("/notsyntaxspec");
1017 printf ("/%d", mcnt
);
1022 printf ("/wordchar");
1026 printf ("/notwordchar");
1038 printf ("?%d", *(p
-1));
1044 printf ("%d:\tend of pattern.\n", p
- start
);
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
);
1072 /* Perhaps we should print the translate table? */
1077 print_double_string (where
, string1
, size1
, string2
, size2
)
1090 if (FIRST_STRING_P (where
))
1092 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1093 putchar (string1
[this_char
]);
1098 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1099 putchar (string2
[this_char
]);
1103 #else /* not DEBUG */
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. */
1134 re_set_syntax (syntax
)
1135 reg_syntax_t syntax
;
1137 reg_syntax_t ret
= re_syntax_options
;
1139 re_syntax_options
= syntax
;
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
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. */
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
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
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;
1230 int re_max_failures
= 4000;
1233 union fail_stack_elt
1235 const unsigned char *pointer
;
1236 unsigned int integer
;
1239 typedef union fail_stack_elt fail_stack_elt_t
;
1243 fail_stack_elt_t
*stack
;
1245 unsigned avail
; /* Offset of next open position. */
1246 unsigned frame
; /* Offset of the cur constructed frame. */
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() \
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) \
1267 fail_stack.size = INIT_FAILURE_ALLOC; \
1268 fail_stack.avail = 0; \
1269 fail_stack.frame = 0; \
1272 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1274 #define INIT_FAIL_STACK() \
1276 fail_stack.avail = 0; \
1277 fail_stack.frame = 0; \
1280 #define RESET_FAIL_STACK()
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) \
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 \
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)), \
1321 /* Push pointer POINTER on FAIL_STACK.
1322 Return 1 if was able to do so and 0 if ran out of memory allocating
1324 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1325 ((FAIL_STACK_FULL () \
1326 && !GROW_FAIL_STACK (FAIL_STACK)) \
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)) \
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) \
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); \
1386 /* Pop a saved register off the stack. */
1387 #define POP_FAILURE_REG() \
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]); \
1396 /* Check that we are not stuck in an infinite loop. */
1397 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
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) \
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)); \
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
1422 Does `return FAILURE_CODE' if runs out of memory. */
1424 #define PUSH_FAILURE_POINT(pattern, string_place) \
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; \
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) \
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'). */
1538 #define PATFETCH(c) \
1541 if (RE_TRANSLATE_P (translate)) c = RE_TRANSLATE (translate, c); \
1545 /* Fetch the next character in the uncompiled pattern, with no
1547 #define PATFETCH_RAW(c) \
1548 do {if (p == pend) return REG_EEND; \
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. */
1561 #define TRANSLATE(d) \
1562 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
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) \
1576 /* Make sure we have one more byte of buffer space and then add C to it. */
1577 #define BUF_PUSH(c) \
1579 GET_BUFFER_SPACE (1); \
1580 *b++ = (unsigned char) (c); \
1584 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1585 #define BUF_PUSH_2(c1, c2) \
1587 GET_BUFFER_SPACE (2); \
1588 *b++ = (unsigned char) (c1); \
1589 *b++ = (unsigned char) (c2); \
1593 /* As with BUF_PUSH_2, except for three bytes. */
1594 #define BUF_PUSH_3(c1, c2, c3) \
1596 GET_BUFFER_SPACE (3); \
1597 *b++ = (unsigned char) (c1); \
1598 *b++ = (unsigned char) (c2); \
1599 *b++ = (unsigned char) (c3); \
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() \
1633 unsigned char *old_buffer = bufp->buffer; \
1634 if (bufp->allocated == MAX_BUF_SIZE) \
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;\
1650 laststart = (laststart - old_buffer) + bufp->buffer; \
1651 if (pending_exact) \
1652 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
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
;
1675 pattern_offset_t begalt_offset
;
1676 pattern_offset_t fixup_alt_jump
;
1677 pattern_offset_t laststart_offset
;
1679 } compile_stack_elt_t
;
1684 compile_stack_elt_t
*stack
;
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) \
1711 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1713 (work_area).allocated += 16 * sizeof (int); \
1714 if ((work_area).table) \
1716 = (int *) realloc ((work_area).table, (work_area).allocated); \
1719 = (int *) malloc ((work_area).allocated); \
1720 if ((work_area).table == 0) \
1721 FREE_STACK_RETURN (REG_ESPACE); \
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) \
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); \
1752 /* Free allocated memory for WORK_AREA. */
1753 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1755 if ((work_area).table) \
1756 free ((work_area).table); \
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) \
1776 while (ISDIGIT (c)) \
1780 num = num * 10 + c - '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)
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
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. */
1830 regex_grow_registers (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
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() \
1872 if (fixup_alt_jump) \
1873 STORE_JUMP (jump, fixup_alt_jump, b); \
1877 /* Return, freeing storage we allocated. */
1878 #define FREE_STACK_RETURN(value) \
1880 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1881 free (compile_stack.stack); \
1885 static reg_errcode_t
1886 regex_compile (pattern
, size
, syntax
, bufp
)
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. */
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. */
1908 /* `const' makes AIX compiler fail. */
1909 unsigned char *p
= pattern
;
1911 re_char
*p
= pattern
;
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
;
1951 DEBUG_PRINT1 ("\nCompiling pattern: ");
1954 unsigned debug_count
;
1956 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1957 putchar (pattern
[debug_count
]);
1962 /* Initialize the compile stack. */
1963 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1964 if (compile_stack
.stack
== NULL
)
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
1983 /* Always count groups, whether or not bufp->no_sub is set. */
1987 /* bufp->multibyte is set before regex_compile is called, so don't alter
1989 #else /* not emacs */
1990 /* Nothing is recognized as a multibyte character. */
1991 bufp
->multibyte
= 0;
1994 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1995 /* Initialize the syntax table. */
1996 init_syntax_once ();
1999 if (bufp
->allocated
== 0)
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);
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. */
2027 if ( /* If at start of pattern, it's an operator. */
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
))
2042 if ( /* If at end of pattern, it's an operator. */
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
))
2057 if ((syntax
& RE_BK_PLUS_QM
)
2058 || (syntax
& RE_LIMITED_OPS
))
2062 /* If there is no previous pattern... */
2065 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2066 FREE_STACK_RETURN (REG_BADRPT
);
2067 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2072 /* 1 means zero (many) matches is allowed. */
2073 boolean zero_times_ok
= 0, many_times_ok
= 0;
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. */
2083 if (!(syntax
& RE_ALL_GREEDY
)
2084 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2088 zero_times_ok
|= c
!= '+';
2089 many_times_ok
|= 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
);
2106 if (!(c1
== '+' || c1
== '?'))
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
)
2129 /* Now we know whether or not zero matches is allowed
2130 and also whether or not two or more matches is allowed. */
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
;
2152 GET_BUFFER_SPACE (6);
2155 STORE_JUMP (on_failure_jump_loop
, b
, b
+ 6);
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);
2165 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2170 /* A simple ? pattern. */
2171 assert (zero_times_ok
);
2172 GET_BUFFER_SPACE (3);
2173 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2177 else /* not greedy */
2178 { /* I wish the greedy and non-greedy cases could be merged. */
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
);
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
);
2199 /* non-greedy a?? */
2200 GET_BUFFER_SPACE (6);
2201 INSERT_JUMP (jump
, laststart
, b
+ 3);
2203 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
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);
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
);
2236 /* Remember the first position in the bracket expression. */
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. */
2254 boolean escaped_char
= false;
2256 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2260 /* \ might escape characters inside [...] and [^...]. */
2261 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2263 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2266 escaped_char
= true;
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)
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
))
2283 c
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, len
);
2286 /* What should we do for the character which is
2287 greater than 0x7F, but not BASE_LEADING_CODE_P?
2290 /* See if we're at the beginning of a possible character
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];
2302 /* If pattern is `[[:'. */
2303 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2308 if (c
== ':' || c
== ']' || p
== pend
2309 || c1
== CHAR_CLASS_MAX_LENGTH
)
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
2319 if (c
== ':' && *p
== ']')
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
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
)
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
;
2373 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
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. */
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. */
2425 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2428 /* Discard the `-'. */
2431 /* Fetch the character which ends the range. */
2433 if (bufp
->multibyte
&& BASE_LEADING_CODE_P (c1
))
2436 c1
= STRING_CHAR_AND_LENGTH (p
, pend
- 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
);
2453 else if (!SAME_CHARSET_P (c
, c1
))
2454 FREE_STACK_RETURN (REG_ERANGE
);
2457 /* Range from C to C. */
2460 /* Set the range ... */
2461 if (SINGLE_BYTE_CHAR_P (c
))
2462 /* ... into bitmap. */
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. */
2476 for (this_char
= range_start
; this_char
<= range_end
;
2478 SET_LIST_BIT (TRANSLATE (this_char
));
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)
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
))
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
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
));
2522 if (syntax
& RE_NO_BK_PARENS
)
2529 if (syntax
& RE_NO_BK_PARENS
)
2536 if (syntax
& RE_NEWLINE_ALT
)
2543 if (syntax
& RE_NO_BK_VBAR
)
2550 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2551 goto handle_interval
;
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. */
2567 if (syntax
& RE_NO_BK_PARENS
)
2568 goto normal_backslash
;
2575 /* Look for a special (?...) construct */
2577 if ((syntax
& RE_SHY_GROUPS
) && c
== '?')
2582 case ':': shy
= 1; break;
2584 /* Only (?:...) is supported right now. */
2585 FREE_STACK_RETURN (REG_BADPAT
);
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
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
;
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
++;
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. */
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
;
2642 FREE_STACK_RETURN (REG_ERPAREN
);
2648 /* See similar code for backslashed left paren above. */
2649 if (COMPILE_STACK_EMPTY
)
2651 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
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
;
2669 = COMPILE_STACK_TOP
.fixup_alt_jump
2670 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
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. */
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
);
2687 case '|': /* `\|'. */
2688 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2689 goto normal_backslash
;
2691 if (syntax
& RE_LIMITED_OPS
)
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);
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:
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'. */
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. */
2723 GET_BUFFER_SPACE (3);
2732 /* If \{ is a literal. */
2733 if (!(syntax
& RE_INTERVALS
)
2734 /* If we're at `\{' and it's not the open-interval
2736 || ((syntax
& RE_INTERVALS
) && (syntax
& RE_NO_BK_BRACES
))
2737 || (p
- 2 == pattern
&& p
== pend
))
2738 goto normal_backslash
;
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;
2751 if (syntax
& RE_NO_BK_BRACES
)
2752 goto unfetch_interval
;
2754 FREE_STACK_RETURN (REG_EBRACE
);
2757 GET_UNSIGNED_NUMBER (lower_bound
);
2761 GET_UNSIGNED_NUMBER (upper_bound
);
2762 if (upper_bound
< 0) upper_bound
= RE_DUP_MAX
;
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
;
2774 FREE_STACK_RETURN (REG_BADBR
);
2777 if (!(syntax
& RE_NO_BK_BRACES
))
2779 if (c
!= '\\') FREE_STACK_RETURN (REG_EBRACE
);
2786 if (syntax
& RE_NO_BK_BRACES
)
2787 goto unfetch_interval
;
2789 FREE_STACK_RETURN (REG_BADBR
);
2792 /* We just parsed a valid interval. */
2794 /* If it's invalid to have no preceding re. */
2797 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2798 FREE_STACK_RETURN (REG_BADRPT
);
2799 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
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);
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>
2821 jump_n <succeed_n addr> <jump count>
2822 (The upper bound and `jump_n' are omitted if
2823 `upper_bound' is 1, though.) */
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,
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
);
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,
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
);
2880 beg_interval
= NULL
;
2885 /* If an invalid interval, match the characters as literals. */
2886 assert (beg_interval
);
2888 beg_interval
= NULL
;
2890 /* normal_char and normal_backslash need `c'. */
2893 if (!(syntax
& RE_NO_BK_BRACES
))
2895 if (p
> pattern
&& p
[-1] == '\\')
2896 goto normal_backslash
;
2901 /* There is no way to specify the before_dot and after_dot
2902 operators. rms says this is ok. --karl */
2910 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2916 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
2922 BUF_PUSH_2 (categoryspec
, c
);
2928 BUF_PUSH_2 (notcategoryspec
, c
);
2935 BUF_PUSH (wordchar
);
2941 BUF_PUSH (notwordchar
);
2954 BUF_PUSH (wordbound
);
2958 BUF_PUSH (notwordbound
);
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
)
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
))
2984 BUF_PUSH_2 (duplicate
, c1
);
2990 if (syntax
& RE_BK_PLUS_QM
)
2993 goto 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. */
3007 /* Expects the character in `c'. */
3009 p1
= p
- 1; /* P1 points the head of C. */
3011 if (bufp
->multibyte
)
3013 c
= STRING_CHAR (p1
, pend
- p1
);
3015 /* Set P to the next character boundary. */
3016 p
+= MULTIBYTE_FORM_LENGTH (p1
, pend
- p1
) - 1;
3019 /* If no exactn currently being built. */
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. */
3042 BUF_PUSH_2 (exactn
, 0);
3043 pending_exact
= b
- 1;
3047 if (! SINGLE_BYTE_CHAR_P (c
))
3049 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
3050 int i
= CHAR_STRING (c
, str
);
3052 for (j
= 0; j
< i
; j
++)
3066 } /* while p != pend */
3069 /* Through the pattern now. */
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
)
3081 free (compile_stack
.stack
);
3083 /* We have succeeded; set the length of the buffer. */
3084 bufp
->used
= b
- bufp
->buffer
;
3089 re_compile_fastmap (bufp
);
3090 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3091 print_compiled_pattern (bufp
);
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
)
3109 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3110 * sizeof (fail_stack_elt_t
));
3113 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3115 * sizeof (fail_stack_elt_t
)));
3118 regex_grow_registers (num_regs
);
3120 #endif /* not MATCH_MAY_ALLOCATE */
3123 } /* regex_compile */
3125 /* Subroutines for `regex_compile'. */
3127 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3130 store_op1 (op
, loc
, 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. */
3143 store_op2 (op
, loc
, 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. */
3158 insert_op1 (op
, loc
, arg
, end
)
3164 register unsigned char *pfrom
= end
;
3165 register unsigned char *pto
= end
+ 3;
3167 while (pfrom
!= loc
)
3170 store_op1 (op
, loc
, arg
);
3174 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3177 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3183 register unsigned char *pfrom
= end
;
3184 register unsigned char *pto
= end
+ 5;
3186 while (pfrom
!= loc
)
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 ^. */
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] == '\\';
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'. */
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;
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. */
3239 group_in_compile_stack (compile_stack
, regnum
)
3240 compile_stack_type compile_stack
;
3245 for (this_element
= compile_stack
.avail
- 1;
3248 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
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
3269 Returns 0 if we succeed, -2 if an internal error. */
3272 re_compile_fastmap (bufp
)
3273 struct re_pattern_buffer
*bufp
;
3276 #ifdef MATCH_MAY_ALLOCATE
3277 fail_stack_type fail_stack
;
3279 #ifndef REGEX_MALLOC
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
;
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
);
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
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:
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 ();
3364 /* We should never be about to go beyond the end of the pattern. */
3367 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
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. */
3379 /* Following are the cases which match a character. These end
3390 int length
= (*p
& 0x7f);;
3393 for (j
= length
* BYTEWIDTH
- 1; j
>= 0; j
--)
3394 if (p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
)))
3400 /* Chars beyond end of map must be allowed. */
3402 int length
= (*p
& 0x7f);;
3405 for (j
= length
* BYTEWIDTH
; j
< (1 << BYTEWIDTH
); j
++)
3408 for (j
= length
* BYTEWIDTH
- 1; j
>= 0; j
--)
3409 if (!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))))
3415 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3416 if (SYNTAX (j
) == Sword
)
3422 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3423 if (SYNTAX (j
) != Sword
)
3428 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3430 if (p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
)))
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. */
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;
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
++)
3472 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3474 if (!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))))
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
))
3487 match_any_multibyte_characters
= true;
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
)
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
;
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
)
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
;
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
++)
3537 /* ... except perhaps newline. */
3538 if (!(bufp
->syntax
& RE_DOT_NEWLINE
))
3539 fastmap
['\n'] = fastmap_newline
;
3541 /* Otherwise, have to check alternative paths. */
3552 /* This match depends on text properties. These end with
3553 aborting optimizations. */
3554 bufp
->can_be_null
= 1;
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
)
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
;
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
)
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
;
3586 simple_char_max
= (1 << BYTEWIDTH
);
3587 for (j
= 0; j
< simple_char_max
; j
++)
3588 if (CHAR_HAS_CATEGORY (j
, k
))
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
;
3598 case notcategoryspec
:
3600 simple_char_max
= (1 << BYTEWIDTH
);
3601 for (j
= 0; j
< simple_char_max
; j
++)
3602 if (!CHAR_HAS_CATEGORY (j
, k
))
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
;
3611 /* All cases after this match the empty string. These end with
3638 EXTRACT_NUMBER_AND_INCR (j
, p
);
3640 /* Backward jumps can only go back to code that we've already
3641 visited. `re_compile' should make sure this is true. */
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
:
3655 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3656 to jump back to "just after here". */
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. */
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 ();
3685 bufp
->can_be_null
= 1;
3689 EXTRACT_NUMBER_AND_INCR (k
, p
); /* Skip the n. */
3690 succeed_n_p
= false;
3697 /* Get to the number of times to succeed. */
3700 /* Increment p past the n for when k != 0. */
3701 EXTRACT_NUMBER_AND_INCR (k
, p
);
3705 succeed_n_p
= true; /* Spaghetti code alert. */
3706 goto handle_on_failure_jump
;
3723 abort (); /* We have listed all the cases. */
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;
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 ();
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
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. */
3757 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3758 struct re_pattern_buffer
*bufp
;
3759 struct re_registers
*regs
;
3761 regoff_t
*starts
, *ends
;
3765 bufp
->regs_allocated
= REGS_REALLOCATE
;
3766 regs
->num_regs
= num_regs
;
3767 regs
->start
= starts
;
3772 bufp
->regs_allocated
= REGS_UNALLOCATED
;
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
;
3787 int size
, startpos
, range
;
3788 struct re_registers
*regs
;
3790 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
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 +
3812 In REGS, return the indices of the virtual concatenation of STRING1
3813 and STRING2 that matched the entire BUFP->buffer and its contained
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
3824 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3825 struct re_pattern_buffer
*bufp
;
3826 const char *str1
, *str2
;
3830 struct re_registers
*regs
;
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
)
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. */
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)
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
;
3878 /* Update the fastmap now if not correct already. */
3879 if (fastmap
&& !bufp
->fastmap_accurate
)
3880 if (re_compile_fastmap (bufp
) == -2)
3883 /* See whether the pattern is anchored. */
3884 if (bufp
->buffer
[0] == begline
)
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);
3896 /* Loop through the string, looking for a place to start matching. */
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])
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;
3928 if (startpos
< size1
&& startpos
+ range
>= size1
)
3929 lim
= range
- (size1
- startpos
);
3931 /* Written out as an if-else to avoid testing `translate'
3933 if (RE_TRANSLATE_P (translate
))
3940 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3943 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3948 range
-= buf_charlen
;
3953 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3960 while (range
> lim
&& !fastmap
[*d
])
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
]))
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
)
3987 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3988 startpos
, regs
, stop
);
3989 #ifndef REGEX_MALLOC
4006 /* Update STARTPOS to the next character boundary. */
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
);
4029 /* Update STARTPOS to the previous character boundary. */
4032 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4035 /* Find the head of multibyte form. */
4036 while (!CHAR_HEAD_P (*p
))
4041 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
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() \
4074 /* End of string2 => fail. */ \
4075 if (dend == end_match_2) \
4077 /* End of string1 => advance to 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)) \
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. */
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))
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() \
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); \
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 *
4140 switch (SWITCH_ENUM_CAST (*p
++))
4151 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4154 p
= CHARSET_RANGE_TABLE (p
- 1);
4155 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4156 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4159 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4166 case notcategoryspec
:
4178 /* Jump over non-matching operations. */
4179 static unsigned char *
4180 skip_noops (p
, pend
)
4181 unsigned char *p
, *pend
;
4186 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4195 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4206 /* Non-zero if "p1 matches something" implies "p2 fails". */
4208 mutually_exclusive_p (bufp
, p1
, p2
)
4209 struct re_pattern_buffer
*bufp
;
4210 unsigned char *p1
, *p2
;
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
))
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");
4246 if (!bufp
->newline_anchor
)
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]);
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)
4271 if (SINGLE_BYTE_CHAR_P (c
))
4273 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4274 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
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. */
4284 DEBUG_PRINT1 (" No match => fast loop.\n");
4288 else if ((re_opcode_t
) *p1
== anychar
4291 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
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
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
4323 /* We win if the charset inside the loop
4324 has no overlap with the one after the loop. */
4327 && idx
< CHARSET_BITMAP_SIZE (p1
));
4329 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4333 || idx
== CHARSET_BITMAP_SIZE (p1
))
4335 DEBUG_PRINT1 (" No match => fast loop.\n");
4339 else if ((re_opcode_t
) *p1
== charset
4340 || (re_opcode_t
) *p1
== charset_not
)
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))))
4353 DEBUG_PRINT1 (" No match => fast loop.\n");
4363 return ((re_opcode_t
) *p1
== syntaxspec
4364 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4368 return ((re_opcode_t
) *p1
== notsyntaxspec
4369 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4372 return (((re_opcode_t
) *p1
== notsyntaxspec
4373 || (re_opcode_t
) *p1
== syntaxspec
)
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]);
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
;
4401 struct re_registers
*regs
;
4403 int result
= re_match_2_internal (bufp
, NULL
, 0, string
, size
,
4408 #endif /* not 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
;
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
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
;
4435 struct re_registers
*regs
;
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);
4447 result
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4453 /* This is a separate function so that we can force an alloca cleanup
4456 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4457 struct re_pattern_buffer
*bufp
;
4458 re_char
*string1
, *string2
;
4461 struct re_registers
*regs
;
4464 /* General temporaries. */
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. */
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. */
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
;
4506 static unsigned failure_id
= 0;
4507 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
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
;
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
;
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
;
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
;
4552 /* Counts the total number of registers pushed. */
4553 unsigned num_regs_pushed
= 0;
4556 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
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. */
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
))
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
)
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'. */
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
)
4618 end1
= string1
+ size1
;
4619 end2
= string2
+ size2
;
4621 /* Compute where to stop matching, within the two strings. */
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
4631 if (size1
> 0 && pos
<= size1
)
4638 d
= string2
+ pos
- size1
;
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. */
4653 DEBUG_PRINT2 ("\n%p: ", p
);
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. */
4673 best_match_p
= d
> match_end
;
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;
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
];
4699 /* If no failure points, don't restore garbage. And if
4700 last match is real best match, don't restore second
4702 else if (best_regs_set
&& !best_match_p
)
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");
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 */
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
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
)
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
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
)
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;
4786 = (regoff_t
) POINTER_TO_OFFSET (regstart
[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
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
);
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. */
4820 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4824 DEBUG_PRINT1 ("EXECUTING succeed.\n");
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. */
4832 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4834 /* Remember the start point to rollback upon failure. */
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
))
4845 int pat_charlen
, buf_charlen
;
4846 unsigned int pat_ch
, buf_ch
;
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
)
4861 mcnt
-= pat_charlen
;
4865 #endif /* not emacs */
4869 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4894 /* Match any character except possibly a newline or a null. */
4898 unsigned int buf_ch
;
4900 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4906 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4908 #endif /* not emacs */
4914 buf_ch
= TRANSLATE (buf_ch
);
4916 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4918 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4919 && buf_ch
== '\000'))
4922 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4931 register unsigned int c
;
4932 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4935 /* Start of actual range_table, or end of bitmap if there is no
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. */
4946 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4951 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
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
);
4964 if (SINGLE_BYTE_CHAR_P (c
))
4965 { /* Lookup bitmap. */
4966 c
= TRANSLATE (c
); /* The character to match. */
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
)))
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
)))
4995 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
4999 if (range_table_exists
)
5000 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5002 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5004 if (!not) goto fail
;
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. */
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
);
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. */
5030 /* The stop_memory opcode represents the end of a group. Its
5031 argument is the same as start_memory's: the register number. */
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
5051 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5053 /* Move past the register number and the inner group count. */
5058 /* \<digit> has been turned into a `duplicate' command which is
5059 followed by the numeric value of <digit> as the register number. */
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
]))
5070 /* Where in input to try to start matching. */
5071 d2
= regstart
[regno
];
5073 /* Remember the start point to rollback upon failure. */
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
);
5086 /* If necessary, advance to next segment in register
5090 if (dend2
== end_match_2
) break;
5091 if (dend2
== regend
[regno
]) break;
5093 /* End of string1 => advance to 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. */
5103 /* How many characters left in this segment to match. */
5106 /* Want how many consecutive characters we can match in
5107 one shot, so, if necessary, adjust the count. */
5108 if (mcnt
> dend2
- d2
)
5111 /* Compare that many; failure if mismatch, else move
5113 if (RE_TRANSLATE_P (translate
)
5114 ? bcmp_translate (d
, d2
, mcnt
, translate
)
5115 : bcmp (d
, d2
, mcnt
))
5120 d
+= mcnt
, d2
+= mcnt
;
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. */
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
)
5140 /* In all other cases, we fail. */
5144 /* endline is the dual of begline. */
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
)
5162 /* Match at the very beginning of the data. */
5164 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5165 if (AT_STRINGS_BEG (d
))
5170 /* Match at the very end of the data. */
5172 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5173 if (AT_STRINGS_END (d
))
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",
5199 PUSH_FAILURE_POINT (p
- 3, NULL
);
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
:
5207 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5208 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5211 CHECK_INFINITE_LOOP (p
- 3, d
);
5212 PUSH_FAILURE_POINT (p
- 3, d
);
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
:
5230 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5231 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5234 PUSH_FAILURE_POINT (p
-3, d
);
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
:
5246 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5247 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
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);
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);
5280 /* Unconditionally jump (without popping any failure points). */
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
);
5291 /* Have to succeed matching what follows at least n times.
5292 After that, handle like `on_failure_jump'. */
5294 EXTRACT_NUMBER (mcnt
, p
+ 2);
5295 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5298 /* Originally, this is how many times we HAVE to succeed. */
5303 STORE_NUMBER_AND_INCR (p
, mcnt
);
5304 DEBUG_PRINT3 (" Setting %p to %d.\n", p
, mcnt
);
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
;
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. */
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. */
5333 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5335 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5337 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5338 DEBUG_PRINT3 (" Setting %p to %d.\n", p1
, mcnt
);
5339 STORE_NUMBER (p1
, mcnt
);
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
))
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. */
5359 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
- 1));
5360 UPDATE_SYNTAX_TABLE (charpos
);
5362 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5363 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5366 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5369 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5370 c2
= STRING_CHAR (d
, dend
- d
);
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
)))
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
))
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. */
5399 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
));
5400 UPDATE_SYNTAX_TABLE (charpos
);
5403 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5404 c2
= STRING_CHAR (d
, dend
- d
);
5407 /* Case 2: S2 is not Sword. */
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
);
5416 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5420 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5422 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
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
))
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. */
5442 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
) - 1);
5443 UPDATE_SYNTAX_TABLE (charpos
);
5445 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5448 /* Case 2: S1 is not Sword. */
5452 /* Case 3: D is not at the end of string ... */
5453 if (!AT_STRINGS_END (d
))
5456 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5457 c2
= STRING_CHAR (d
, dend
- d
);
5459 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5463 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5465 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5473 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5474 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5479 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5480 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5485 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5486 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5491 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt
);
5496 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5502 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
));
5503 UPDATE_SYNTAX_TABLE (pos1
);
5510 /* we must concern about multibyte form, ... */
5511 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5513 /* everything should be handled as ASCII, even though it
5514 looks like multibyte form. */
5517 if (SYNTAX (c
) != (enum syntaxcode
) mcnt
)
5524 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt
);
5526 goto matchnotsyntax
;
5529 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5535 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
));
5536 UPDATE_SYNTAX_TABLE (pos1
);
5543 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5547 if (SYNTAX (c
) == (enum syntaxcode
) mcnt
)
5554 DEBUG_PRINT2 ("EXECUTING categoryspec %d.\n", *p
);
5561 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5565 if (!CHAR_HAS_CATEGORY (c
, mcnt
))
5571 case notcategoryspec
:
5572 DEBUG_PRINT2 ("EXECUTING notcategoryspec %d.\n", *p
);
5579 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5583 if (CHAR_HAS_CATEGORY (c
, mcnt
))
5589 #else /* not emacs */
5591 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5593 if (!WORDCHAR_P (d
))
5599 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5605 #endif /* not emacs */
5610 continue; /* Successfully executed one pattern command; keep going. */
5613 /* We goto here if a matching operation fails. */
5616 if (!FAIL_STACK_EMPTY ())
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
:
5633 continue_failure_jump
:
5634 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5642 assert (p
>= bufp
->buffer
&& p
<= pend
);
5644 if (d
>= string1
&& d
<= end1
)
5648 break; /* Matching at this starting point really fails. */
5652 goto restore_best_regs
;
5656 return -1; /* Failure to match. */
5659 /* Subroutine definitions for re_match_2. */
5661 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5662 bytes; nonzero otherwise. */
5665 bcmp_translate (s1
, s2
, len
, translate
)
5666 unsigned char *s1
, *s2
;
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
;
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
))
5687 p1
+= p1_charlen
, p2
+= p2_charlen
;
5690 if (p1
!= p1_end
|| p2
!= p2_end
)
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. */
5708 re_compile_pattern (pattern
, length
, bufp
)
5709 const char *pattern
;
5711 struct re_pattern_buffer
*bufp
;
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
5724 /* Match anchors at newline. */
5725 bufp
->newline_anchor
= 1;
5727 ret
= regex_compile (pattern
, length
, re_syntax_options
, bufp
);
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
;
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. */
5756 if (!re_comp_buf
.buffer
)
5757 return gettext ("No previous regular expression");
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
);
5784 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5785 return (char *) gettext (re_error_msgid
[(int) ret
]);
5796 const int len
= strlen (s
);
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. */
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
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
)
5843 const char *pattern
;
5848 = (cflags
& REG_EXTENDED
) ?
5849 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5851 /* regex_compile will allocate the space for the compiled pattern. */
5853 preg
->allocated
= 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
5862 if (cflags
& REG_ICASE
)
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
;
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;
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
;
5904 /* regexec searches for a given pattern, specified by PREG, in the
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
;
5923 regmatch_t pmatch
[];
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
;
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
? ®s
: (struct re_registers
*) 0);
5956 /* Copy the register information to the POSIX structure. */
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. */
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. */
5984 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5986 const regex_t
*preg
;
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. */
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;
6013 strcpy (errbuf
, msg
);
6020 /* Free dynamically allocated space used by PREG. */
6026 if (preg
->buffer
!= NULL
)
6027 free (preg
->buffer
);
6028 preg
->buffer
= NULL
;
6030 preg
->allocated
= 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 */