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 - clean up multibyte issues
24 - structure the opcode space into opcode+flag.
25 - merge with glibc's regex.[ch]
28 /* AIX requires this to be the first thing in the file. */
29 #if defined (_AIX) && !defined (REGEX_MALLOC)
37 /* Converts the pointer to the char to BEG-based offset from the start. */
38 #define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
39 #define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
41 #define PTR_TO_OFFSET(d) 0
48 /* We need this for `regex.h', and perhaps for the Emacs include files. */
49 #include <sys/types.h>
51 /* This is for other GNU distributions with internationalized messages. */
52 #if HAVE_LIBINTL_H || defined (_LIBC)
55 # define gettext(msgid) (msgid)
59 /* This define is so xgettext can find the internationalizable
61 #define gettext_noop(String) String
64 /* The `emacs' switch turns on certain matching commands
65 that make sense only in Emacs. */
71 /* Make syntax table lookup grant data in gl_state. */
72 #define SYNTAX_ENTRY_VIA_PROPERTY
78 #define malloc xmalloc
79 #define realloc xrealloc
82 #define RE_STRING_CHAR(p, s) \
83 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
87 /* If we are not linking with Emacs proper,
88 we can't use the relocating allocator
89 even if config.h says that we can. */
92 #if defined (STDC_HEADERS) || defined (_LIBC)
99 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
100 If nothing else has been done, use the method below. */
101 #ifdef INHIBIT_STRING_HEADER
102 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
103 #if !defined (bzero) && !defined (bcopy)
104 #undef INHIBIT_STRING_HEADER
109 /* This is the normal way of making sure we have a bcopy and a bzero.
110 This is used in most programs--a few other programs avoid this
111 by defining INHIBIT_STRING_HEADER. */
112 #ifndef INHIBIT_STRING_HEADER
113 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
116 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
119 #define bcopy(s, d, n) memcpy ((d), (s), (n))
122 #define bzero(s, n) memset ((s), 0, (n))
129 /* Define the syntax stuff for \<, \>, etc. */
131 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
132 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
134 #ifdef SWITCH_ENUM_BUG
135 #define SWITCH_ENUM_CAST(x) ((int)(x))
137 #define SWITCH_ENUM_CAST(x) (x)
142 extern char *re_syntax_table
;
144 #else /* not SYNTAX_TABLE */
146 /* How many characters in the character set. */
147 #define CHAR_SET_SIZE 256
149 static char re_syntax_table
[CHAR_SET_SIZE
];
160 bzero (re_syntax_table
, sizeof re_syntax_table
);
162 for (c
= 'a'; c
<= 'z'; c
++)
163 re_syntax_table
[c
] = Sword
;
165 for (c
= 'A'; c
<= 'Z'; c
++)
166 re_syntax_table
[c
] = Sword
;
168 for (c
= '0'; c
<= '9'; c
++)
169 re_syntax_table
[c
] = Sword
;
171 re_syntax_table
['_'] = Sword
;
176 #endif /* not SYNTAX_TABLE */
178 #define SYNTAX(c) re_syntax_table[c]
180 /* Dummy macros for non-Emacs environments. */
181 #define BASE_LEADING_CODE_P(c) (0)
182 #define CHAR_CHARSET(c) 0
183 #define CHARSET_LEADING_CODE_BASE(c) 0
184 #define WORD_BOUNDARY_P(c1, c2) (0)
185 #define CHAR_HEAD_P(p) (1)
186 #define SINGLE_BYTE_CHAR_P(c) (1)
187 #define SAME_CHARSET_P(c1, c2) (1)
188 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
189 #define STRING_CHAR(p, s) (*(p))
190 #define RE_STRING_CHAR STRING_CHAR
191 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
192 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
193 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
194 #endif /* not emacs */
197 #define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
198 #define RE_TRANSLATE_P(TBL) (TBL)
201 /* Get the interface, including the syntax bits. */
204 /* isalpha etc. are used for the character classes. */
209 /* 1 if C is an ASCII character. */
210 #define IS_REAL_ASCII(c) ((c) < 0200)
212 /* 1 if C is a unibyte character. */
213 #define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
215 /* The Emacs definitions should not be directly affected by locales. */
217 /* In Emacs, these are only used for single-byte characters. */
218 #define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
219 #define ISCNTRL(c) ((c) < ' ')
220 #define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
221 || ((c) >= 'a' && (c) <= 'f') \
222 || ((c) >= 'A' && (c) <= 'F'))
224 /* This is only used for single-byte characters. */
225 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
227 /* The rest must handle multibyte characters. */
229 #define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
230 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
233 #define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
234 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
237 #define ISALNUM(c) (IS_REAL_ASCII (c) \
238 ? (((c) >= 'a' && (c) <= 'z') \
239 || ((c) >= 'A' && (c) <= 'Z') \
240 || ((c) >= '0' && (c) <= '9')) \
241 : SYNTAX (c) == Sword)
243 #define ISALPHA(c) (IS_REAL_ASCII (c) \
244 ? (((c) >= 'a' && (c) <= 'z') \
245 || ((c) >= 'A' && (c) <= 'Z')) \
246 : SYNTAX (c) == Sword)
248 #define ISLOWER(c) (LOWERCASEP (c))
250 #define ISPUNCT(c) (IS_REAL_ASCII (c) \
251 ? ((c) > ' ' && (c) < 0177 \
252 && !(((c) >= 'a' && (c) <= 'z') \
253 || ((c) >= 'A' && (c) <= 'Z') \
254 || ((c) >= '0' && (c) <= '9'))) \
255 : SYNTAX (c) != Sword)
257 #define ISSPACE(c) (SYNTAX (c) == Swhitespace)
259 #define ISUPPER(c) (UPPERCASEP (c))
261 #define ISWORD(c) (SYNTAX (c) == Sword)
263 #else /* not emacs */
265 /* Jim Meyering writes:
267 "... Some ctype macros are valid only for character codes that
268 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
269 using /bin/cc or gcc but without giving an ansi option). So, all
270 ctype uses should be through macros like ISPRINT... If
271 STDC_HEADERS is defined, then autoconf has verified that the ctype
272 macros don't need to be guarded with references to isascii. ...
273 Defining isascii to 1 should let any compiler worth its salt
274 eliminate the && through constant folding." */
276 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
279 #define ISASCII(c) isascii(c)
282 /* 1 if C is an ASCII character. */
283 #define IS_REAL_ASCII(c) ((c) < 0200)
285 /* This distinction is not meaningful, except in Emacs. */
286 #define ISUNIBYTE(c) 1
288 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
289 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
290 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
293 #define ISBLANK(c) (ISASCII (c) && isblank (c))
295 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
298 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
300 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
303 #define ISPRINT(c) (ISASCII (c) && isprint (c))
304 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
305 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
306 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
307 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
308 #define ISLOWER(c) (ISASCII (c) && islower (c))
309 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
310 #define ISSPACE(c) (ISASCII (c) && isspace (c))
311 #define ISUPPER(c) (ISASCII (c) && isupper (c))
312 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
314 #define ISWORD(c) ISALPHA(c)
316 #endif /* not emacs */
319 #define NULL (void *)0
322 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
323 since ours (we hope) works properly with all combinations of
324 machines, compilers, `char' and `unsigned char' argument types.
325 (Per Bothner suggested the basic approach.) */
326 #undef SIGN_EXTEND_CHAR
328 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
329 #else /* not __STDC__ */
330 /* As in Harbison and Steele. */
331 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
334 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
335 use `alloca' instead of `malloc'. This is because using malloc in
336 re_search* or re_match* could cause memory leaks when C-g is used in
337 Emacs; also, malloc is slower and causes storage fragmentation. On
338 the other hand, malloc is more portable, and easier to debug.
340 Because we sometimes use alloca, some routines have to be macros,
341 not functions -- `alloca'-allocated space disappears at the end of the
342 function it is called in. */
346 #define REGEX_ALLOCATE malloc
347 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
348 #define REGEX_FREE free
350 #else /* not REGEX_MALLOC */
352 /* Emacs already defines alloca, sometimes. */
355 /* Make alloca work the best possible way. */
357 #define alloca __builtin_alloca
358 #else /* not __GNUC__ */
361 #else /* not __GNUC__ or HAVE_ALLOCA_H */
362 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
363 #ifndef _AIX /* Already did AIX, up at the top. */
365 #endif /* not _AIX */
367 #endif /* not HAVE_ALLOCA_H */
368 #endif /* not __GNUC__ */
370 #endif /* not alloca */
372 #define REGEX_ALLOCATE alloca
374 /* Assumes a `char *destination' variable. */
375 #define REGEX_REALLOCATE(source, osize, nsize) \
376 (destination = (char *) alloca (nsize), \
377 bcopy (source, destination, osize), \
380 /* No need to do anything to free, after alloca. */
381 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
383 #endif /* not REGEX_MALLOC */
385 /* Define how to allocate the failure stack. */
387 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
389 #define REGEX_ALLOCATE_STACK(size) \
390 r_alloc (&failure_stack_ptr, (size))
391 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
392 r_re_alloc (&failure_stack_ptr, (nsize))
393 #define REGEX_FREE_STACK(ptr) \
394 r_alloc_free (&failure_stack_ptr)
396 #else /* not using relocating allocator */
400 #define REGEX_ALLOCATE_STACK malloc
401 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
402 #define REGEX_FREE_STACK free
404 #else /* not REGEX_MALLOC */
406 #define REGEX_ALLOCATE_STACK alloca
408 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
409 REGEX_REALLOCATE (source, osize, nsize)
410 /* No need to explicitly free anything. */
411 #define REGEX_FREE_STACK(arg) ((void)0)
413 #endif /* not REGEX_MALLOC */
414 #endif /* not using relocating allocator */
417 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
418 `string1' or just past its end. This works if PTR is NULL, which is
420 #define FIRST_STRING_P(ptr) \
421 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
423 /* (Re)Allocate N items of type T using malloc, or fail. */
424 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
425 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
426 #define RETALLOC_IF(addr, n, t) \
427 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
428 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
430 #define BYTEWIDTH 8 /* In bits. */
432 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
436 #define MAX(a, b) ((a) > (b) ? (a) : (b))
437 #define MIN(a, b) ((a) < (b) ? (a) : (b))
439 /* Type of source-pattern and string chars. */
440 typedef const unsigned char re_char
;
442 typedef char boolean
;
446 static int re_match_2_internal ();
448 /* These are the command codes that appear in compiled regular
449 expressions. Some opcodes are followed by argument bytes. A
450 command code can specify any interpretation whatsoever for its
451 arguments. Zero bytes may appear in the compiled regular expression. */
457 /* Succeed right away--no more backtracking. */
460 /* Followed by one byte giving n, then by n literal bytes. */
463 /* Matches any (more or less) character. */
466 /* Matches any one char belonging to specified set. First
467 following byte is number of bitmap bytes. Then come bytes
468 for a bitmap saying which chars are in. Bits in each byte
469 are ordered low-bit-first. A character is in the set if its
470 bit is 1. A character too large to have a bit in the map is
471 automatically not in the set.
473 If the length byte has the 0x80 bit set, then that stuff
474 is followed by a range table:
475 2 bytes of flags for character sets (low 8 bits, high 8 bits)
476 See RANGE_TABLE_WORK_BITS below.
477 2 bytes, the number of pairs that follow
478 pairs, each 2 multibyte characters,
479 each multibyte character represented as 3 bytes. */
482 /* Same parameters as charset, but match any character that is
483 not one of those specified. */
486 /* Start remembering the text that is matched, for storing in a
487 register. Followed by one byte with the register number, in
488 the range 0 to one less than the pattern buffer's re_nsub
492 /* Stop remembering the text that is matched and store it in a
493 memory register. Followed by one byte with the register
494 number, in the range 0 to one less than `re_nsub' in the
498 /* Match a duplicate of something remembered. Followed by one
499 byte containing the register number. */
502 /* Fail unless at beginning of line. */
505 /* Fail unless at end of line. */
508 /* Succeeds if at beginning of buffer (if emacs) or at beginning
509 of string to be matched (if not). */
512 /* Analogously, for end of buffer/string. */
515 /* Followed by two byte relative address to which to jump. */
518 /* Followed by two-byte relative address of place to resume at
519 in case of failure. */
522 /* Like on_failure_jump, but pushes a placeholder instead of the
523 current string position when executed. */
524 on_failure_keep_string_jump
,
526 /* Just like `on_failure_jump', except that it checks that we
527 don't get stuck in an infinite loop (matching an empty string
529 on_failure_jump_loop
,
531 /* Just like `on_failure_jump_loop', except that it checks for
532 a different kind of loop (the kind that shows up with non-greedy
533 operators). This operation has to be immediately preceded
535 on_failure_jump_nastyloop
,
537 /* A smart `on_failure_jump' used for greedy * and + operators.
538 It analyses the loop before which it is put and if the
539 loop does not require backtracking, it changes itself to
540 `on_failure_keep_string_jump' and short-circuits the loop,
541 else it just defaults to changing itself into `on_failure_jump'.
542 It assumes that it is pointing to just past a `jump'. */
543 on_failure_jump_smart
,
545 /* Followed by two-byte relative address and two-byte number n.
546 After matching N times, jump to the address upon failure.
547 Does not work if N starts at 0: use on_failure_jump_loop
551 /* Followed by two-byte relative address, and two-byte number n.
552 Jump to the address N times, then fail. */
555 /* Set the following two-byte relative address to the
556 subsequent two-byte number. The address *includes* the two
560 wordbeg
, /* Succeeds if at word beginning. */
561 wordend
, /* Succeeds if at word end. */
563 wordbound
, /* Succeeds if at a word boundary. */
564 notwordbound
, /* Succeeds if not at a word boundary. */
566 /* Matches any character whose syntax is specified. Followed by
567 a byte which contains a syntax code, e.g., Sword. */
570 /* Matches any character whose syntax is not that specified. */
574 ,before_dot
, /* Succeeds if before point. */
575 at_dot
, /* Succeeds if at point. */
576 after_dot
, /* Succeeds if after point. */
578 /* Matches any character whose category-set contains the specified
579 category. The operator is followed by a byte which contains a
580 category code (mnemonic ASCII character). */
583 /* Matches any character whose category-set does not contain the
584 specified category. The operator is followed by a byte which
585 contains the category code (mnemonic ASCII character). */
590 /* Common operations on the compiled pattern. */
592 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
594 #define STORE_NUMBER(destination, number) \
596 (destination)[0] = (number) & 0377; \
597 (destination)[1] = (number) >> 8; \
600 /* Same as STORE_NUMBER, except increment DESTINATION to
601 the byte after where the number is stored. Therefore, DESTINATION
602 must be an lvalue. */
604 #define STORE_NUMBER_AND_INCR(destination, number) \
606 STORE_NUMBER (destination, number); \
607 (destination) += 2; \
610 /* Put into DESTINATION a number stored in two contiguous bytes starting
613 #define EXTRACT_NUMBER(destination, source) \
615 (destination) = *(source) & 0377; \
616 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
621 extract_number (dest
, source
)
623 unsigned char *source
;
625 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
626 *dest
= *source
& 0377;
630 #ifndef EXTRACT_MACROS /* To debug the macros. */
631 #undef EXTRACT_NUMBER
632 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
633 #endif /* not EXTRACT_MACROS */
637 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
638 SOURCE must be an lvalue. */
640 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
642 EXTRACT_NUMBER (destination, source); \
648 extract_number_and_incr (destination
, source
)
650 unsigned char **source
;
652 extract_number (destination
, *source
);
656 #ifndef EXTRACT_MACROS
657 #undef EXTRACT_NUMBER_AND_INCR
658 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
659 extract_number_and_incr (&dest, &src)
660 #endif /* not EXTRACT_MACROS */
664 /* Store a multibyte character in three contiguous bytes starting
665 DESTINATION, and increment DESTINATION to the byte after where the
666 character is stored. Therefore, DESTINATION must be an lvalue. */
668 #define STORE_CHARACTER_AND_INCR(destination, character) \
670 (destination)[0] = (character) & 0377; \
671 (destination)[1] = ((character) >> 8) & 0377; \
672 (destination)[2] = (character) >> 16; \
673 (destination) += 3; \
676 /* Put into DESTINATION a character stored in three contiguous bytes
677 starting at SOURCE. */
679 #define EXTRACT_CHARACTER(destination, source) \
681 (destination) = ((source)[0] \
682 | ((source)[1] << 8) \
683 | ((source)[2] << 16)); \
687 /* Macros for charset. */
689 /* Size of bitmap of charset P in bytes. P is a start of charset,
690 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
691 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
693 /* Nonzero if charset P has range table. */
694 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
696 /* Return the address of range table of charset P. But not the start
697 of table itself, but the before where the number of ranges is
698 stored. `2 +' means to skip re_opcode_t and size of bitmap,
699 and the 2 bytes of flags at the start of the range table. */
700 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
702 /* Extract the bit flags that start a range table. */
703 #define CHARSET_RANGE_TABLE_BITS(p) \
704 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
705 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
707 /* Test if C is listed in the bitmap of charset P. */
708 #define CHARSET_LOOKUP_BITMAP(p, c) \
709 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
710 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
712 /* Return the address of end of RANGE_TABLE. COUNT is number of
713 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
714 is start of range and end of range. `* 3' is size of each start
716 #define CHARSET_RANGE_TABLE_END(range_table, count) \
717 ((range_table) + (count) * 2 * 3)
719 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
720 COUNT is number of ranges in RANGE_TABLE. */
721 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
724 int range_start, range_end; \
726 unsigned char *range_table_end \
727 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
729 for (p = (range_table); p < range_table_end; p += 2 * 3) \
731 EXTRACT_CHARACTER (range_start, p); \
732 EXTRACT_CHARACTER (range_end, p + 3); \
734 if (range_start <= (c) && (c) <= range_end) \
743 /* Test if C is in range table of CHARSET. The flag NOT is negated if
744 C is listed in it. */
745 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
748 /* Number of ranges in range table. */ \
750 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
752 EXTRACT_NUMBER_AND_INCR (count, range_table); \
753 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
757 /* If DEBUG is defined, Regex prints many voluminous messages about what
758 it is doing (if the variable `debug' is nonzero). If linked with the
759 main program in `iregex.c', you can enter patterns and strings
760 interactively. And if linked with the main program in `main.c' and
761 the other test files, you can run the already-written tests. */
765 /* We use standard I/O for debugging. */
768 /* It is useful to test things that ``must'' be true when debugging. */
771 static int debug
= -100000;
773 #define DEBUG_STATEMENT(e) e
774 #define DEBUG_PRINT1(x) if (debug > 0) printf (x)
775 #define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
776 #define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
777 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
778 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
779 if (debug > 0) print_partial_compiled_pattern (s, e)
780 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
781 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
784 /* Print the fastmap in human-readable form. */
787 print_fastmap (fastmap
)
790 unsigned was_a_range
= 0;
793 while (i
< (1 << BYTEWIDTH
))
799 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
815 /* Print a compiled pattern string in human-readable form, starting at
816 the START pointer into it and ending just before the pointer END. */
819 print_partial_compiled_pattern (start
, end
)
820 unsigned char *start
;
824 unsigned char *p
= start
;
825 unsigned char *pend
= end
;
833 /* Loop over pattern commands. */
836 printf ("%d:\t", p
- start
);
838 switch ((re_opcode_t
) *p
++)
850 printf ("/exactn/%d", mcnt
);
860 printf ("/start_memory/%d", *p
++);
864 printf ("/stop_memory/%d", *p
++);
868 printf ("/duplicate/%d", *p
++);
878 register int c
, last
= -100;
879 register int in_range
= 0;
880 int length
= CHARSET_BITMAP_SIZE (p
- 1);
881 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
883 printf ("/charset [%s",
884 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
886 assert (p
+ *p
< pend
);
888 for (c
= 0; c
< 256; c
++)
890 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
892 /* Are we starting a range? */
893 if (last
+ 1 == c
&& ! in_range
)
898 /* Have we broken a range? */
899 else if (last
+ 1 != c
&& in_range
)
921 printf ("has-range-table");
923 /* ??? Should print the range table; for now, just skip it. */
924 p
+= 2; /* skip range table bits */
925 EXTRACT_NUMBER_AND_INCR (count
, p
);
926 p
= CHARSET_RANGE_TABLE_END (p
, count
);
939 case on_failure_jump
:
940 extract_number_and_incr (&mcnt
, &p
);
941 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
944 case on_failure_keep_string_jump
:
945 extract_number_and_incr (&mcnt
, &p
);
946 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
949 case on_failure_jump_nastyloop
:
950 extract_number_and_incr (&mcnt
, &p
);
951 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
954 case on_failure_jump_loop
:
955 extract_number_and_incr (&mcnt
, &p
);
956 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
959 case on_failure_jump_smart
:
960 extract_number_and_incr (&mcnt
, &p
);
961 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
965 extract_number_and_incr (&mcnt
, &p
);
966 printf ("/jump to %d", p
+ mcnt
- start
);
970 extract_number_and_incr (&mcnt
, &p
);
971 extract_number_and_incr (&mcnt2
, &p
);
972 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
976 extract_number_and_incr (&mcnt
, &p
);
977 extract_number_and_incr (&mcnt2
, &p
);
978 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
982 extract_number_and_incr (&mcnt
, &p
);
983 extract_number_and_incr (&mcnt2
, &p
);
984 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
988 printf ("/wordbound");
992 printf ("/notwordbound");
1000 printf ("/wordend");
1003 printf ("/syntaxspec");
1005 printf ("/%d", mcnt
);
1009 printf ("/notsyntaxspec");
1011 printf ("/%d", mcnt
);
1016 printf ("/before_dot");
1024 printf ("/after_dot");
1028 printf ("/categoryspec");
1030 printf ("/%d", mcnt
);
1033 case notcategoryspec
:
1034 printf ("/notcategoryspec");
1036 printf ("/%d", mcnt
);
1049 printf ("?%d", *(p
-1));
1055 printf ("%d:\tend of pattern.\n", p
- start
);
1060 print_compiled_pattern (bufp
)
1061 struct re_pattern_buffer
*bufp
;
1063 unsigned char *buffer
= bufp
->buffer
;
1065 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1066 printf ("%ld bytes used/%ld bytes allocated.\n", bufp
->used
, bufp
->allocated
);
1068 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1070 printf ("fastmap: ");
1071 print_fastmap (bufp
->fastmap
);
1074 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1075 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1076 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1077 printf ("newline_anchor: %d\n", bufp
->newline_anchor
);
1078 printf ("no_sub: %d\t", bufp
->no_sub
);
1079 printf ("not_bol: %d\t", bufp
->not_bol
);
1080 printf ("not_eol: %d\t", bufp
->not_eol
);
1081 printf ("syntax: %d\n", bufp
->syntax
);
1083 /* Perhaps we should print the translate table? */
1088 print_double_string (where
, string1
, size1
, string2
, size2
)
1101 if (FIRST_STRING_P (where
))
1103 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1104 putchar (string1
[this_char
]);
1109 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1110 putchar (string2
[this_char
]);
1114 #else /* not DEBUG */
1119 #define DEBUG_STATEMENT(e)
1120 #define DEBUG_PRINT1(x)
1121 #define DEBUG_PRINT2(x1, x2)
1122 #define DEBUG_PRINT3(x1, x2, x3)
1123 #define DEBUG_PRINT4(x1, x2, x3, x4)
1124 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1125 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1127 #endif /* not DEBUG */
1129 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1130 also be assigned to arbitrarily: each pattern buffer stores its own
1131 syntax, so it can be changed between regex compilations. */
1132 /* This has no initializer because initialized variables in Emacs
1133 become read-only after dumping. */
1134 reg_syntax_t re_syntax_options
;
1137 /* Specify the precise syntax of regexps for compilation. This provides
1138 for compatibility for various utilities which historically have
1139 different, incompatible syntaxes.
1141 The argument SYNTAX is a bit mask comprised of the various bits
1142 defined in regex.h. We return the old syntax. */
1145 re_set_syntax (syntax
)
1146 reg_syntax_t syntax
;
1148 reg_syntax_t ret
= re_syntax_options
;
1150 re_syntax_options
= syntax
;
1154 /* This table gives an error message for each of the error codes listed
1155 in regex.h. Obviously the order here has to be same as there.
1156 POSIX doesn't require that we do anything for REG_NOERROR,
1157 but why not be nice? */
1159 static const char *re_error_msgid
[] =
1161 gettext_noop ("Success"), /* REG_NOERROR */
1162 gettext_noop ("No match"), /* REG_NOMATCH */
1163 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1164 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1165 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1166 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1167 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1168 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1169 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1170 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1171 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1172 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1173 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1174 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1175 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1176 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1177 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1180 /* Avoiding alloca during matching, to placate r_alloc. */
1182 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1183 searching and matching functions should not call alloca. On some
1184 systems, alloca is implemented in terms of malloc, and if we're
1185 using the relocating allocator routines, then malloc could cause a
1186 relocation, which might (if the strings being searched are in the
1187 ralloc heap) shift the data out from underneath the regexp
1190 Here's another reason to avoid allocation: Emacs
1191 processes input from X in a signal handler; processing X input may
1192 call malloc; if input arrives while a matching routine is calling
1193 malloc, then we're scrod. But Emacs can't just block input while
1194 calling matching routines; then we don't notice interrupts when
1195 they come in. So, Emacs blocks input around all regexp calls
1196 except the matching calls, which it leaves unprotected, in the
1197 faith that they will not malloc. */
1199 /* Normally, this is fine. */
1200 #define MATCH_MAY_ALLOCATE
1202 /* When using GNU C, we are not REALLY using the C alloca, no matter
1203 what config.h may say. So don't take precautions for it. */
1208 /* The match routines may not allocate if (1) they would do it with malloc
1209 and (2) it's not safe for them to use malloc.
1210 Note that if REL_ALLOC is defined, matching would not use malloc for the
1211 failure stack, but we would still use it for the register vectors;
1212 so REL_ALLOC should not affect this. */
1213 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1214 #undef MATCH_MAY_ALLOCATE
1218 /* Failure stack declarations and macros; both re_compile_fastmap and
1219 re_match_2 use a failure stack. These have to be macros because of
1220 REGEX_ALLOCATE_STACK. */
1223 /* Approximate number of failure points for which to initially allocate space
1224 when matching. If this number is exceeded, we allocate more
1225 space, so it is not a hard limit. */
1226 #ifndef INIT_FAILURE_ALLOC
1227 #define INIT_FAILURE_ALLOC 20
1230 /* Roughly the maximum number of failure points on the stack. Would be
1231 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1232 This is a variable only so users of regex can assign to it; we never
1233 change it ourselves. */
1234 #if defined (MATCH_MAY_ALLOCATE)
1235 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1236 whose default stack limit is 2mb. In order for a larger
1237 value to work reliably, you have to try to make it accord
1238 with the process stack limit. */
1239 int re_max_failures
= 40000;
1241 int re_max_failures
= 4000;
1244 union fail_stack_elt
1246 const unsigned char *pointer
;
1247 unsigned int integer
;
1250 typedef union fail_stack_elt fail_stack_elt_t
;
1254 fail_stack_elt_t
*stack
;
1256 unsigned avail
; /* Offset of next open position. */
1257 unsigned frame
; /* Offset of the cur constructed frame. */
1260 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1261 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1262 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1265 /* Define macros to initialize and free the failure stack.
1266 Do `return -2' if the alloc fails. */
1268 #ifdef MATCH_MAY_ALLOCATE
1269 #define INIT_FAIL_STACK() \
1271 fail_stack.stack = (fail_stack_elt_t *) \
1272 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1273 * sizeof (fail_stack_elt_t)); \
1275 if (fail_stack.stack == NULL) \
1278 fail_stack.size = INIT_FAILURE_ALLOC; \
1279 fail_stack.avail = 0; \
1280 fail_stack.frame = 0; \
1283 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1285 #define INIT_FAIL_STACK() \
1287 fail_stack.avail = 0; \
1288 fail_stack.frame = 0; \
1291 #define RESET_FAIL_STACK() ((void)0)
1295 /* Double the size of FAIL_STACK, up to a limit
1296 which allows approximately `re_max_failures' items.
1298 Return 1 if succeeds, and 0 if either ran out of memory
1299 allocating space for it or it was already too large.
1301 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1303 /* Factor to increase the failure stack size by
1304 when we increase it.
1305 This used to be 2, but 2 was too wasteful
1306 because the old discarded stacks added up to as much space
1307 were as ultimate, maximum-size stack. */
1308 #define FAIL_STACK_GROWTH_FACTOR 4
1310 #define GROW_FAIL_STACK(fail_stack) \
1311 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1312 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1314 : ((fail_stack).stack \
1315 = (fail_stack_elt_t *) \
1316 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1317 (fail_stack).size * sizeof (fail_stack_elt_t), \
1318 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1319 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1320 * FAIL_STACK_GROWTH_FACTOR))), \
1322 (fail_stack).stack == NULL \
1324 : ((fail_stack).size \
1325 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1326 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1327 * FAIL_STACK_GROWTH_FACTOR)) \
1328 / sizeof (fail_stack_elt_t)), \
1332 /* Push pointer POINTER on FAIL_STACK.
1333 Return 1 if was able to do so and 0 if ran out of memory allocating
1335 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1336 ((FAIL_STACK_FULL () \
1337 && !GROW_FAIL_STACK (FAIL_STACK)) \
1339 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1341 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1343 /* Push a pointer value onto the failure stack.
1344 Assumes the variable `fail_stack'. Probably should only
1345 be called from within `PUSH_FAILURE_POINT'. */
1346 #define PUSH_FAILURE_POINTER(item) \
1347 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1349 /* This pushes an integer-valued item onto the failure stack.
1350 Assumes the variable `fail_stack'. Probably should only
1351 be called from within `PUSH_FAILURE_POINT'. */
1352 #define PUSH_FAILURE_INT(item) \
1353 fail_stack.stack[fail_stack.avail++].integer = (item)
1355 /* Push a fail_stack_elt_t value onto the failure stack.
1356 Assumes the variable `fail_stack'. Probably should only
1357 be called from within `PUSH_FAILURE_POINT'. */
1358 #define PUSH_FAILURE_ELT(item) \
1359 fail_stack.stack[fail_stack.avail++] = (item)
1361 /* These three POP... operations complement the three PUSH... operations.
1362 All assume that `fail_stack' is nonempty. */
1363 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1364 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1365 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1367 /* Individual items aside from the registers. */
1368 #define NUM_NONREG_ITEMS 3
1370 /* Used to examine the stack (to detect infinite loops). */
1371 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1372 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1373 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1374 #define TOP_FAILURE_HANDLE() fail_stack.frame
1377 #define ENSURE_FAIL_STACK(space) \
1378 while (REMAINING_AVAIL_SLOTS <= space) { \
1379 if (!GROW_FAIL_STACK (fail_stack)) \
1381 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1382 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1385 /* Push register NUM onto the stack. */
1386 #define PUSH_FAILURE_REG(num) \
1388 char *destination; \
1389 ENSURE_FAIL_STACK(3); \
1390 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1391 num, regstart[num], regend[num]); \
1392 PUSH_FAILURE_POINTER (regstart[num]); \
1393 PUSH_FAILURE_POINTER (regend[num]); \
1394 PUSH_FAILURE_INT (num); \
1397 /* Pop a saved register off the stack. */
1398 #define POP_FAILURE_REG() \
1400 int reg = POP_FAILURE_INT (); \
1401 regend[reg] = POP_FAILURE_POINTER (); \
1402 regstart[reg] = POP_FAILURE_POINTER (); \
1403 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1404 reg, regstart[reg], regend[reg]); \
1407 /* Check that we are not stuck in an infinite loop. */
1408 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1410 int failure = TOP_FAILURE_HANDLE(); \
1411 /* Check for infinite matching loops */ \
1412 while (failure > 0 && \
1413 (FAILURE_STR (failure) == string_place \
1414 || FAILURE_STR (failure) == NULL)) \
1416 assert (FAILURE_PAT (failure) >= bufp->buffer \
1417 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1418 if (FAILURE_PAT (failure) == pat_cur) \
1420 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1421 failure = NEXT_FAILURE_HANDLE(failure); \
1423 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1426 /* Push the information about the state we will need
1427 if we ever fail back to it.
1429 Requires variables fail_stack, regstart, regend and
1430 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1433 Does `return FAILURE_CODE' if runs out of memory. */
1435 #define PUSH_FAILURE_POINT(pattern, string_place) \
1437 char *destination; \
1438 /* Must be int, so when we don't save any registers, the arithmetic \
1439 of 0 + -1 isn't done as unsigned. */ \
1441 DEBUG_STATEMENT (failure_id++); \
1442 DEBUG_STATEMENT (nfailure_points_pushed++); \
1443 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1444 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1445 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1447 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1449 DEBUG_PRINT1 ("\n"); \
1451 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1452 PUSH_FAILURE_INT (fail_stack.frame); \
1454 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1455 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1456 DEBUG_PRINT1 ("'\n"); \
1457 PUSH_FAILURE_POINTER (string_place); \
1459 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1460 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1461 PUSH_FAILURE_POINTER (pattern); \
1463 /* Close the frame by moving the frame pointer past it. */ \
1464 fail_stack.frame = fail_stack.avail; \
1467 /* Estimate the size of data pushed by a typical failure stack entry.
1468 An estimate is all we need, because all we use this for
1469 is to choose a limit for how big to make the failure stack. */
1471 #define TYPICAL_FAILURE_SIZE 20
1473 /* How many items can still be added to the stack without overflowing it. */
1474 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1477 /* Pops what PUSH_FAIL_STACK pushes.
1479 We restore into the parameters, all of which should be lvalues:
1480 STR -- the saved data position.
1481 PAT -- the saved pattern position.
1482 REGSTART, REGEND -- arrays of string positions.
1484 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1485 `pend', `string1', `size1', `string2', and `size2'. */
1487 #define POP_FAILURE_POINT(str, pat) \
1489 assert (!FAIL_STACK_EMPTY ()); \
1491 /* Remove failure points and point to how many regs pushed. */ \
1492 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1493 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1494 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1496 /* Pop the saved registers. */ \
1497 while (fail_stack.frame < fail_stack.avail) \
1498 POP_FAILURE_REG (); \
1500 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1501 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1502 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1504 /* If the saved string location is NULL, it came from an \
1505 on_failure_keep_string_jump opcode, and we want to throw away the \
1506 saved NULL, thus retaining our current position in the string. */ \
1507 str = (re_char *) POP_FAILURE_POINTER (); \
1508 DEBUG_PRINT2 (" Popping string %p: `", str); \
1509 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1510 DEBUG_PRINT1 ("'\n"); \
1512 fail_stack.frame = POP_FAILURE_INT (); \
1513 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1515 assert (fail_stack.avail >= 0); \
1516 assert (fail_stack.frame <= fail_stack.avail); \
1518 DEBUG_STATEMENT (nfailure_points_popped++); \
1519 } while (0) /* POP_FAILURE_POINT */
1523 /* Registers are set to a sentinel when they haven't yet matched. */
1524 #define REG_UNSET_VALUE NULL
1525 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1527 /* Subroutine declarations and macros for regex_compile. */
1529 static void store_op1
_RE_ARGS((re_opcode_t op
, unsigned char *loc
, int arg
));
1530 static void store_op2
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1531 int arg1
, int arg2
));
1532 static void insert_op1
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1533 int arg
, unsigned char *end
));
1534 static void insert_op2
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1535 int arg1
, int arg2
, unsigned char *end
));
1536 static boolean at_begline_loc_p
_RE_ARGS((const unsigned char *pattern
,
1537 const unsigned char *p
,
1538 reg_syntax_t syntax
));
1539 static boolean at_endline_loc_p
_RE_ARGS((const unsigned char *p
,
1540 const unsigned char *pend
,
1541 reg_syntax_t syntax
));
1542 static unsigned char *skip_one_char
_RE_ARGS((unsigned char *p
));
1543 static int analyse_first
_RE_ARGS((unsigned char *p
, unsigned char *pend
,
1544 char *fastmap
, const int multibyte
));
1546 /* Fetch the next character in the uncompiled pattern---translating it
1547 if necessary. Also cast from a signed character in the constant
1548 string passed to us by the user to an unsigned char that we can use
1549 as an array index (in, e.g., `translate'). */
1550 #define PATFETCH(c) \
1553 if (RE_TRANSLATE_P (translate)) c = RE_TRANSLATE (translate, c); \
1556 /* Fetch the next character in the uncompiled pattern, with no
1558 #define PATFETCH_RAW(c) \
1559 do {if (p == pend) return REG_EEND; \
1563 /* Go backwards one character in the pattern. */
1564 #define PATUNFETCH p--
1567 /* If `translate' is non-null, return translate[D], else just D. We
1568 cast the subscript to translate because some data is declared as
1569 `char *', to avoid warnings when a string constant is passed. But
1570 when we use a character as a subscript we must make it unsigned. */
1572 #define TRANSLATE(d) \
1573 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1577 /* Macros for outputting the compiled pattern into `buffer'. */
1579 /* If the buffer isn't allocated when it comes in, use this. */
1580 #define INIT_BUF_SIZE 32
1582 /* Make sure we have at least N more bytes of space in buffer. */
1583 #define GET_BUFFER_SPACE(n) \
1584 while (b - bufp->buffer + (n) > bufp->allocated) \
1587 /* Make sure we have one more byte of buffer space and then add C to it. */
1588 #define BUF_PUSH(c) \
1590 GET_BUFFER_SPACE (1); \
1591 *b++ = (unsigned char) (c); \
1595 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1596 #define BUF_PUSH_2(c1, c2) \
1598 GET_BUFFER_SPACE (2); \
1599 *b++ = (unsigned char) (c1); \
1600 *b++ = (unsigned char) (c2); \
1604 /* As with BUF_PUSH_2, except for three bytes. */
1605 #define BUF_PUSH_3(c1, c2, c3) \
1607 GET_BUFFER_SPACE (3); \
1608 *b++ = (unsigned char) (c1); \
1609 *b++ = (unsigned char) (c2); \
1610 *b++ = (unsigned char) (c3); \
1614 /* Store a jump with opcode OP at LOC to location TO. We store a
1615 relative address offset by the three bytes the jump itself occupies. */
1616 #define STORE_JUMP(op, loc, to) \
1617 store_op1 (op, loc, (to) - (loc) - 3)
1619 /* Likewise, for a two-argument jump. */
1620 #define STORE_JUMP2(op, loc, to, arg) \
1621 store_op2 (op, loc, (to) - (loc) - 3, arg)
1623 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1624 #define INSERT_JUMP(op, loc, to) \
1625 insert_op1 (op, loc, (to) - (loc) - 3, b)
1627 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1628 #define INSERT_JUMP2(op, loc, to, arg) \
1629 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1632 /* This is not an arbitrary limit: the arguments which represent offsets
1633 into the pattern are two bytes long. So if 2^16 bytes turns out to
1634 be too small, many things would have to change. */
1635 #define MAX_BUF_SIZE (1L << 16)
1638 /* Extend the buffer by twice its current size via realloc and
1639 reset the pointers that pointed into the old block to point to the
1640 correct places in the new one. If extending the buffer results in it
1641 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1642 #define EXTEND_BUFFER() \
1644 unsigned char *old_buffer = bufp->buffer; \
1645 if (bufp->allocated == MAX_BUF_SIZE) \
1647 bufp->allocated <<= 1; \
1648 if (bufp->allocated > MAX_BUF_SIZE) \
1649 bufp->allocated = MAX_BUF_SIZE; \
1650 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1651 if (bufp->buffer == NULL) \
1652 return REG_ESPACE; \
1653 /* If the buffer moved, move all the pointers into it. */ \
1654 if (old_buffer != bufp->buffer) \
1656 b = (b - old_buffer) + bufp->buffer; \
1657 begalt = (begalt - old_buffer) + bufp->buffer; \
1658 if (fixup_alt_jump) \
1659 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1661 laststart = (laststart - old_buffer) + bufp->buffer; \
1662 if (pending_exact) \
1663 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1668 /* Since we have one byte reserved for the register number argument to
1669 {start,stop}_memory, the maximum number of groups we can report
1670 things about is what fits in that byte. */
1671 #define MAX_REGNUM 255
1673 /* But patterns can have more than `MAX_REGNUM' registers. We just
1674 ignore the excess. */
1675 typedef unsigned regnum_t
;
1678 /* Macros for the compile stack. */
1680 /* Since offsets can go either forwards or backwards, this type needs to
1681 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1682 typedef int pattern_offset_t
;
1686 pattern_offset_t begalt_offset
;
1687 pattern_offset_t fixup_alt_jump
;
1688 pattern_offset_t laststart_offset
;
1690 } compile_stack_elt_t
;
1695 compile_stack_elt_t
*stack
;
1697 unsigned avail
; /* Offset of next open position. */
1698 } compile_stack_type
;
1701 #define INIT_COMPILE_STACK_SIZE 32
1703 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1704 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1706 /* The next available element. */
1707 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1710 /* Structure to manage work area for range table. */
1711 struct range_table_work_area
1713 int *table
; /* actual work area. */
1714 int allocated
; /* allocated size for work area in bytes. */
1715 int used
; /* actually used size in words. */
1716 int bits
; /* flag to record character classes */
1719 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1720 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1722 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1724 (work_area).allocated += 16 * sizeof (int); \
1725 if ((work_area).table) \
1727 = (int *) realloc ((work_area).table, (work_area).allocated); \
1730 = (int *) malloc ((work_area).allocated); \
1731 if ((work_area).table == 0) \
1732 FREE_STACK_RETURN (REG_ESPACE); \
1736 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1737 (work_area).bits |= (bit)
1739 /* These bits represent the various character classes such as [:alnum:]
1740 in a charset's range table. */
1741 #define BIT_ALNUM 0x1
1742 #define BIT_ALPHA 0x2
1743 #define BIT_WORD 0x4
1744 #define BIT_ASCII 0x8
1745 #define BIT_NONASCII 0x10
1746 #define BIT_GRAPH 0x20
1747 #define BIT_LOWER 0x40
1748 #define BIT_PRINT 0x80
1749 #define BIT_PUNCT 0x100
1750 #define BIT_SPACE 0x200
1751 #define BIT_UPPER 0x400
1752 #define BIT_UNIBYTE 0x800
1753 #define BIT_MULTIBYTE 0x1000
1755 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1756 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1758 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1759 (work_area).table[(work_area).used++] = (range_start); \
1760 (work_area).table[(work_area).used++] = (range_end); \
1763 /* Free allocated memory for WORK_AREA. */
1764 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1766 if ((work_area).table) \
1767 free ((work_area).table); \
1770 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1771 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1772 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1773 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1776 /* Set the bit for character C in a list. */
1777 #define SET_LIST_BIT(c) \
1778 (b[((unsigned char) (c)) / BYTEWIDTH] \
1779 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1782 /* Get the next unsigned number in the uncompiled pattern. */
1783 #define GET_UNSIGNED_NUMBER(num) \
1784 do { if (p != pend) \
1787 while (ISDIGIT (c)) \
1791 num = num * 10 + c - '0'; \
1799 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1801 #define IS_CHAR_CLASS(string) \
1802 (STREQ (string, "alpha") || STREQ (string, "upper") \
1803 || STREQ (string, "lower") || STREQ (string, "digit") \
1804 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1805 || STREQ (string, "space") || STREQ (string, "print") \
1806 || STREQ (string, "punct") || STREQ (string, "graph") \
1807 || STREQ (string, "cntrl") || STREQ (string, "blank") \
1808 || STREQ (string, "word") \
1809 || STREQ (string, "ascii") || STREQ (string, "nonascii") \
1810 || STREQ (string, "unibyte") || STREQ (string, "multibyte"))
1812 /* QUIT is only used on NTemacs. */
1813 #if !defined (WINDOWSNT) || !defined (emacs)
1818 #ifndef MATCH_MAY_ALLOCATE
1820 /* If we cannot allocate large objects within re_match_2_internal,
1821 we make the fail stack and register vectors global.
1822 The fail stack, we grow to the maximum size when a regexp
1824 The register vectors, we adjust in size each time we
1825 compile a regexp, according to the number of registers it needs. */
1827 static fail_stack_type fail_stack
;
1829 /* Size with which the following vectors are currently allocated.
1830 That is so we can make them bigger as needed,
1831 but never make them smaller. */
1832 static int regs_allocated_size
;
1834 static re_char
** regstart
, ** regend
;
1835 static re_char
**best_regstart
, **best_regend
;
1837 /* Make the register vectors big enough for NUM_REGS registers,
1838 but don't make them smaller. */
1841 regex_grow_registers (num_regs
)
1844 if (num_regs
> regs_allocated_size
)
1846 RETALLOC_IF (regstart
, num_regs
, re_char
*);
1847 RETALLOC_IF (regend
, num_regs
, re_char
*);
1848 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
1849 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
1851 regs_allocated_size
= num_regs
;
1855 #endif /* not MATCH_MAY_ALLOCATE */
1857 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
1861 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1862 Returns one of error codes defined in `regex.h', or zero for success.
1864 Assumes the `allocated' (and perhaps `buffer') and `translate'
1865 fields are set in BUFP on entry.
1867 If it succeeds, results are put in BUFP (if it returns an error, the
1868 contents of BUFP are undefined):
1869 `buffer' is the compiled pattern;
1870 `syntax' is set to SYNTAX;
1871 `used' is set to the length of the compiled pattern;
1872 `fastmap_accurate' is zero;
1873 `re_nsub' is the number of subexpressions in PATTERN;
1874 `not_bol' and `not_eol' are zero;
1876 The `fastmap' and `newline_anchor' fields are neither
1877 examined nor set. */
1879 /* Insert the `jump' from the end of last alternative to "here".
1880 The space for the jump has already been allocated. */
1881 #define FIXUP_ALT_JUMP() \
1883 if (fixup_alt_jump) \
1884 STORE_JUMP (jump, fixup_alt_jump, b); \
1888 /* Return, freeing storage we allocated. */
1889 #define FREE_STACK_RETURN(value) \
1891 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1892 free (compile_stack.stack); \
1896 static reg_errcode_t
1897 regex_compile (pattern
, size
, syntax
, bufp
)
1900 reg_syntax_t syntax
;
1901 struct re_pattern_buffer
*bufp
;
1903 /* We fetch characters from PATTERN here. Even though PATTERN is
1904 `char *' (i.e., signed), we declare these variables as unsigned, so
1905 they can be reliably used as array indices. */
1906 register unsigned int c
, c1
;
1908 /* A random temporary spot in PATTERN. */
1911 /* Points to the end of the buffer, where we should append. */
1912 register unsigned char *b
;
1914 /* Keeps track of unclosed groups. */
1915 compile_stack_type compile_stack
;
1917 /* Points to the current (ending) position in the pattern. */
1919 /* `const' makes AIX compiler fail. */
1920 unsigned char *p
= pattern
;
1922 re_char
*p
= pattern
;
1924 re_char
*pend
= pattern
+ size
;
1926 /* How to translate the characters in the pattern. */
1927 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
1929 /* Address of the count-byte of the most recently inserted `exactn'
1930 command. This makes it possible to tell if a new exact-match
1931 character can be added to that command or if the character requires
1932 a new `exactn' command. */
1933 unsigned char *pending_exact
= 0;
1935 /* Address of start of the most recently finished expression.
1936 This tells, e.g., postfix * where to find the start of its
1937 operand. Reset at the beginning of groups and alternatives. */
1938 unsigned char *laststart
= 0;
1940 /* Address of beginning of regexp, or inside of last group. */
1941 unsigned char *begalt
;
1943 /* Place in the uncompiled pattern (i.e., the {) to
1944 which to go back if the interval is invalid. */
1945 re_char
*beg_interval
;
1947 /* Address of the place where a forward jump should go to the end of
1948 the containing expression. Each alternative of an `or' -- except the
1949 last -- ends with a forward jump of this sort. */
1950 unsigned char *fixup_alt_jump
= 0;
1952 /* Counts open-groups as they are encountered. Remembered for the
1953 matching close-group on the compile stack, so the same register
1954 number is put in the stop_memory as the start_memory. */
1955 regnum_t regnum
= 0;
1957 /* Work area for range table of charset. */
1958 struct range_table_work_area range_table_work
;
1962 DEBUG_PRINT1 ("\nCompiling pattern: ");
1965 unsigned debug_count
;
1967 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1968 putchar (pattern
[debug_count
]);
1973 /* Initialize the compile stack. */
1974 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1975 if (compile_stack
.stack
== NULL
)
1978 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
1979 compile_stack
.avail
= 0;
1981 range_table_work
.table
= 0;
1982 range_table_work
.allocated
= 0;
1984 /* Initialize the pattern buffer. */
1985 bufp
->syntax
= syntax
;
1986 bufp
->fastmap_accurate
= 0;
1987 bufp
->not_bol
= bufp
->not_eol
= 0;
1989 /* Set `used' to zero, so that if we return an error, the pattern
1990 printer (for debugging) will think there's no pattern. We reset it
1994 /* Always count groups, whether or not bufp->no_sub is set. */
1998 /* bufp->multibyte is set before regex_compile is called, so don't alter
2000 #else /* not emacs */
2001 /* Nothing is recognized as a multibyte character. */
2002 bufp
->multibyte
= 0;
2005 #if !defined (emacs) && !defined (SYNTAX_TABLE)
2006 /* Initialize the syntax table. */
2007 init_syntax_once ();
2010 if (bufp
->allocated
== 0)
2013 { /* If zero allocated, but buffer is non-null, try to realloc
2014 enough space. This loses if buffer's address is bogus, but
2015 that is the user's responsibility. */
2016 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2019 { /* Caller did not allocate a buffer. Do it for them. */
2020 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2022 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2024 bufp
->allocated
= INIT_BUF_SIZE
;
2027 begalt
= b
= bufp
->buffer
;
2029 /* Loop through the uncompiled pattern until we're at the end. */
2038 if ( /* If at start of pattern, it's an operator. */
2040 /* If context independent, it's an operator. */
2041 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2042 /* Otherwise, depends on what's come before. */
2043 || at_begline_loc_p (pattern
, p
, syntax
))
2053 if ( /* If at end of pattern, it's an operator. */
2055 /* If context independent, it's an operator. */
2056 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2057 /* Otherwise, depends on what's next. */
2058 || at_endline_loc_p (p
, pend
, syntax
))
2068 if ((syntax
& RE_BK_PLUS_QM
)
2069 || (syntax
& RE_LIMITED_OPS
))
2073 /* If there is no previous pattern... */
2076 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2077 FREE_STACK_RETURN (REG_BADRPT
);
2078 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2083 /* 1 means zero (many) matches is allowed. */
2084 boolean zero_times_ok
= 0, many_times_ok
= 0;
2087 /* If there is a sequence of repetition chars, collapse it
2088 down to just one (the right one). We can't combine
2089 interval operators with these because of, e.g., `a{2}*',
2090 which should only match an even number of `a's. */
2094 if (!(syntax
& RE_ALL_GREEDY
)
2095 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2099 zero_times_ok
|= c
!= '+';
2100 many_times_ok
|= c
!= '?';
2106 || (!(syntax
& RE_BK_PLUS_QM
)
2107 && (*p
== '+' || *p
== '?')))
2109 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2112 FREE_STACK_RETURN (REG_EESCAPE
);
2113 if (p
[1] == '+' || p
[1] == '?')
2114 PATFETCH (c
); /* Gobble up the backslash. */
2120 /* 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;
2138 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2139 on_failure_jump
: on_failure_jump_loop
;
2140 assert (skip_one_char (laststart
) <= b
);
2142 if (!zero_times_ok
&& simple
)
2143 { /* Since simple * loops can be made faster by using
2144 on_failure_keep_string_jump, we turn simple P+
2145 into PP* if P is simple. */
2146 unsigned char *p1
, *p2
;
2147 startoffset
= b
- laststart
;
2148 GET_BUFFER_SPACE (startoffset
);
2149 p1
= b
; p2
= laststart
;
2155 GET_BUFFER_SPACE (6);
2158 STORE_JUMP (ofj
, b
, b
+ 6);
2160 /* Simple * loops can use on_failure_keep_string_jump
2161 depending on what follows. But since we don't know
2162 that yet, we leave the decision up to
2163 on_failure_jump_smart. */
2164 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2165 laststart
+ startoffset
, b
+ 6);
2167 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2172 /* A simple ? pattern. */
2173 assert (zero_times_ok
);
2174 GET_BUFFER_SPACE (3);
2175 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2179 else /* not greedy */
2180 { /* I wish the greedy and non-greedy cases could be merged. */
2182 GET_BUFFER_SPACE (7); /* We might use less. */
2185 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2187 /* The non-greedy multiple match looks like a repeat..until:
2188 we only need a conditional jump at the end of the loop */
2189 if (emptyp
) BUF_PUSH (no_op
);
2190 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2191 : on_failure_jump
, b
, laststart
);
2195 /* The repeat...until naturally matches one or more.
2196 To also match zero times, we need to first jump to
2197 the end of the loop (its conditional jump). */
2198 INSERT_JUMP (jump
, laststart
, b
);
2204 /* non-greedy a?? */
2205 INSERT_JUMP (jump
, laststart
, b
+ 3);
2207 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2224 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2226 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2228 /* Ensure that we have enough space to push a charset: the
2229 opcode, the length count, and the bitset; 34 bytes in all. */
2230 GET_BUFFER_SPACE (34);
2234 /* We test `*p == '^' twice, instead of using an if
2235 statement, so we only need one BUF_PUSH. */
2236 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2240 /* Remember the first position in the bracket expression. */
2243 /* Push the number of bytes in the bitmap. */
2244 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2246 /* Clear the whole map. */
2247 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2249 /* charset_not matches newline according to a syntax bit. */
2250 if ((re_opcode_t
) b
[-2] == charset_not
2251 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2252 SET_LIST_BIT ('\n');
2254 /* Read in characters and ranges, setting map bits. */
2258 boolean escaped_char
= false;
2260 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2264 /* \ might escape characters inside [...] and [^...]. */
2265 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2267 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2270 escaped_char
= true;
2274 /* Could be the end of the bracket expression. If it's
2275 not (i.e., when the bracket expression is `[]' so
2276 far), the ']' character bit gets set way below. */
2277 if (c
== ']' && p
!= p1
+ 1)
2281 /* If C indicates start of multibyte char, get the
2282 actual character code in C, and set the pattern
2283 pointer P to the next character boundary. */
2284 if (bufp
->multibyte
&& BASE_LEADING_CODE_P (c
))
2287 c
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, len
);
2290 /* What should we do for the character which is
2291 greater than 0x7F, but not BASE_LEADING_CODE_P?
2294 /* See if we're at the beginning of a possible character
2297 else if (!escaped_char
&&
2298 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2300 /* Leave room for the null. */
2301 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2302 const unsigned char *class_beg
;
2308 /* If pattern is `[[:'. */
2309 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2314 if (c
== ':' || c
== ']' || p
== pend
2315 || c1
== CHAR_CLASS_MAX_LENGTH
)
2321 /* If isn't a word bracketed by `[:' and `:]':
2322 undo the ending character, the letters, and
2323 leave the leading `:' and `[' (but set bits for
2325 if (c
== ':' && *p
== ']')
2328 boolean is_alnum
= STREQ (str
, "alnum");
2329 boolean is_alpha
= STREQ (str
, "alpha");
2330 boolean is_ascii
= STREQ (str
, "ascii");
2331 boolean is_blank
= STREQ (str
, "blank");
2332 boolean is_cntrl
= STREQ (str
, "cntrl");
2333 boolean is_digit
= STREQ (str
, "digit");
2334 boolean is_graph
= STREQ (str
, "graph");
2335 boolean is_lower
= STREQ (str
, "lower");
2336 boolean is_multibyte
= STREQ (str
, "multibyte");
2337 boolean is_nonascii
= STREQ (str
, "nonascii");
2338 boolean is_print
= STREQ (str
, "print");
2339 boolean is_punct
= STREQ (str
, "punct");
2340 boolean is_space
= STREQ (str
, "space");
2341 boolean is_unibyte
= STREQ (str
, "unibyte");
2342 boolean is_upper
= STREQ (str
, "upper");
2343 boolean is_word
= STREQ (str
, "word");
2344 boolean is_xdigit
= STREQ (str
, "xdigit");
2346 if (!IS_CHAR_CLASS (str
))
2347 FREE_STACK_RETURN (REG_ECTYPE
);
2349 /* Throw away the ] at the end of the character
2353 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2355 /* Most character classes in a multibyte match
2356 just set a flag. Exceptions are is_blank,
2357 is_digit, is_cntrl, and is_xdigit, since
2358 they can only match ASCII characters. We
2359 don't need to handle them for multibyte. */
2361 if (bufp
->multibyte
)
2365 if (is_alnum
) bit
= BIT_ALNUM
;
2366 if (is_alpha
) bit
= BIT_ALPHA
;
2367 if (is_ascii
) bit
= BIT_ASCII
;
2368 if (is_graph
) bit
= BIT_GRAPH
;
2369 if (is_lower
) bit
= BIT_LOWER
;
2370 if (is_multibyte
) bit
= BIT_MULTIBYTE
;
2371 if (is_nonascii
) bit
= BIT_NONASCII
;
2372 if (is_print
) bit
= BIT_PRINT
;
2373 if (is_punct
) bit
= BIT_PUNCT
;
2374 if (is_space
) bit
= BIT_SPACE
;
2375 if (is_unibyte
) bit
= BIT_UNIBYTE
;
2376 if (is_upper
) bit
= BIT_UPPER
;
2377 if (is_word
) bit
= BIT_WORD
;
2379 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2383 /* Handle character classes for ASCII characters. */
2384 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++)
2386 int translated
= TRANSLATE (ch
);
2387 /* This was split into 3 if's to
2388 avoid an arbitrary limit in some compiler. */
2389 if ( (is_alnum
&& ISALNUM (ch
))
2390 || (is_alpha
&& ISALPHA (ch
))
2391 || (is_blank
&& ISBLANK (ch
))
2392 || (is_cntrl
&& ISCNTRL (ch
)))
2393 SET_LIST_BIT (translated
);
2394 if ( (is_digit
&& ISDIGIT (ch
))
2395 || (is_graph
&& ISGRAPH (ch
))
2396 || (is_lower
&& ISLOWER (ch
))
2397 || (is_print
&& ISPRINT (ch
)))
2398 SET_LIST_BIT (translated
);
2399 if ( (is_punct
&& ISPUNCT (ch
))
2400 || (is_space
&& ISSPACE (ch
))
2401 || (is_upper
&& ISUPPER (ch
))
2402 || (is_xdigit
&& ISXDIGIT (ch
)))
2403 SET_LIST_BIT (translated
);
2404 if ( (is_ascii
&& IS_REAL_ASCII (ch
))
2405 || (is_nonascii
&& !IS_REAL_ASCII (ch
))
2406 || (is_unibyte
&& ISUNIBYTE (ch
))
2407 || (is_multibyte
&& !ISUNIBYTE (ch
)))
2408 SET_LIST_BIT (translated
);
2410 if ( (is_word
&& ISWORD (ch
)))
2411 SET_LIST_BIT (translated
);
2414 /* Repeat the loop. */
2419 /* Go back to right after the "[:". */
2423 /* Because the `:' may starts the range, we
2424 can't simply set bit and repeat the loop.
2425 Instead, just set it to C and handle below. */
2430 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2433 /* Discard the `-'. */
2436 /* Fetch the character which ends the range. */
2438 if (bufp
->multibyte
&& BASE_LEADING_CODE_P (c1
))
2441 c1
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, len
);
2445 if (SINGLE_BYTE_CHAR_P (c
)
2446 && ! SINGLE_BYTE_CHAR_P (c1
))
2448 /* Handle a range such as \177-\377 in multibyte mode.
2449 Split that into two ranges,,
2450 the low one ending at 0237, and the high one
2451 starting at ...040. */
2452 /* Unless I'm missing something,
2453 this line is useless. -sm
2454 int c1_base = (c1 & ~0177) | 040; */
2455 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2458 else if (!SAME_CHARSET_P (c
, c1
))
2459 FREE_STACK_RETURN (REG_ERANGE
);
2462 /* Range from C to C. */
2465 /* Set the range ... */
2466 if (SINGLE_BYTE_CHAR_P (c
))
2467 /* ... into bitmap. */
2470 int range_start
= c
, range_end
= c1
;
2472 /* If the start is after the end, the range is empty. */
2473 if (range_start
> range_end
)
2475 if (syntax
& RE_NO_EMPTY_RANGES
)
2476 FREE_STACK_RETURN (REG_ERANGE
);
2477 /* Else, repeat the loop. */
2481 for (this_char
= range_start
; this_char
<= range_end
;
2483 SET_LIST_BIT (TRANSLATE (this_char
));
2487 /* ... into range table. */
2488 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2491 /* Discard any (non)matching list bytes that are all 0 at the
2492 end of the map. Decrease the map-length byte too. */
2493 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2497 /* Build real range table from work area. */
2498 if (RANGE_TABLE_WORK_USED (range_table_work
)
2499 || RANGE_TABLE_WORK_BITS (range_table_work
))
2502 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2504 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2505 bytes for flags, two for COUNT, and three bytes for
2507 GET_BUFFER_SPACE (4 + used
* 3);
2509 /* Indicate the existence of range table. */
2510 laststart
[1] |= 0x80;
2512 /* Store the character class flag bits into the range table.
2513 If not in emacs, these flag bits are always 0. */
2514 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2515 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2517 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2518 for (i
= 0; i
< used
; i
++)
2519 STORE_CHARACTER_AND_INCR
2520 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2527 if (syntax
& RE_NO_BK_PARENS
)
2534 if (syntax
& RE_NO_BK_PARENS
)
2541 if (syntax
& RE_NEWLINE_ALT
)
2548 if (syntax
& RE_NO_BK_VBAR
)
2555 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2556 goto handle_interval
;
2562 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2564 /* Do not translate the character after the \, so that we can
2565 distinguish, e.g., \B from \b, even if we normally would
2566 translate, e.g., B to b. */
2572 if (syntax
& RE_NO_BK_PARENS
)
2573 goto normal_backslash
;
2580 /* Look for a special (?...) construct */
2581 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2583 PATFETCH (c
); /* Gobble up the '?'. */
2587 case ':': shy
= 1; break;
2589 /* Only (?:...) is supported right now. */
2590 FREE_STACK_RETURN (REG_BADPAT
);
2601 if (COMPILE_STACK_FULL
)
2603 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2604 compile_stack_elt_t
);
2605 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2607 compile_stack
.size
<<= 1;
2610 /* These are the values to restore when we hit end of this
2611 group. They are all relative offsets, so that if the
2612 whole pattern moves because of realloc, they will still
2614 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2615 COMPILE_STACK_TOP
.fixup_alt_jump
2616 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2617 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2618 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2621 start_memory for groups beyond the last one we can
2622 represent in the compiled pattern. */
2623 if (regnum
<= MAX_REGNUM
&& !shy
)
2624 BUF_PUSH_2 (start_memory
, regnum
);
2626 compile_stack
.avail
++;
2631 /* If we've reached MAX_REGNUM groups, then this open
2632 won't actually generate any code, so we'll have to
2633 clear pending_exact explicitly. */
2639 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2641 if (COMPILE_STACK_EMPTY
)
2643 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2644 goto normal_backslash
;
2646 FREE_STACK_RETURN (REG_ERPAREN
);
2652 /* See similar code for backslashed left paren above. */
2653 if (COMPILE_STACK_EMPTY
)
2655 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2658 FREE_STACK_RETURN (REG_ERPAREN
);
2661 /* Since we just checked for an empty stack above, this
2662 ``can't happen''. */
2663 assert (compile_stack
.avail
!= 0);
2665 /* We don't just want to restore into `regnum', because
2666 later groups should continue to be numbered higher,
2667 as in `(ab)c(de)' -- the second group is #2. */
2668 regnum_t this_group_regnum
;
2670 compile_stack
.avail
--;
2671 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2673 = COMPILE_STACK_TOP
.fixup_alt_jump
2674 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2676 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2677 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2678 /* If we've reached MAX_REGNUM groups, then this open
2679 won't actually generate any code, so we'll have to
2680 clear pending_exact explicitly. */
2683 /* We're at the end of the group, so now we know how many
2684 groups were inside this one. */
2685 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2686 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2691 case '|': /* `\|'. */
2692 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2693 goto normal_backslash
;
2695 if (syntax
& RE_LIMITED_OPS
)
2698 /* Insert before the previous alternative a jump which
2699 jumps to this alternative if the former fails. */
2700 GET_BUFFER_SPACE (3);
2701 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2705 /* The alternative before this one has a jump after it
2706 which gets executed if it gets matched. Adjust that
2707 jump so it will jump to this alternative's analogous
2708 jump (put in below, which in turn will jump to the next
2709 (if any) alternative's such jump, etc.). The last such
2710 jump jumps to the correct final destination. A picture:
2716 If we are at `b', then fixup_alt_jump right now points to a
2717 three-byte space after `a'. We'll put in the jump, set
2718 fixup_alt_jump to right after `b', and leave behind three
2719 bytes which we'll fill in when we get to after `c'. */
2723 /* Mark and leave space for a jump after this alternative,
2724 to be filled in later either by next alternative or
2725 when know we're at the end of a series of alternatives. */
2727 GET_BUFFER_SPACE (3);
2736 /* If \{ is a literal. */
2737 if (!(syntax
& RE_INTERVALS
)
2738 /* If we're at `\{' and it's not the open-interval
2740 || (syntax
& RE_NO_BK_BRACES
)
2741 /* What is that? -sm */
2742 /* || (p - 2 == pattern && p == pend) */)
2743 goto normal_backslash
;
2747 /* If got here, then the syntax allows intervals. */
2749 /* At least (most) this many matches must be made. */
2750 int lower_bound
= 0, upper_bound
= -1;
2756 if (syntax
& RE_NO_BK_BRACES
)
2757 goto unfetch_interval
;
2759 FREE_STACK_RETURN (REG_EBRACE
);
2762 GET_UNSIGNED_NUMBER (lower_bound
);
2765 GET_UNSIGNED_NUMBER (upper_bound
);
2767 /* Interval such as `{1}' => match exactly once. */
2768 upper_bound
= lower_bound
;
2770 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2771 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
2773 if (syntax
& RE_NO_BK_BRACES
)
2774 goto unfetch_interval
;
2776 FREE_STACK_RETURN (REG_BADBR
);
2779 if (!(syntax
& RE_NO_BK_BRACES
))
2781 if (c
!= '\\') FREE_STACK_RETURN (REG_EBRACE
);
2788 if (syntax
& RE_NO_BK_BRACES
)
2789 goto unfetch_interval
;
2791 FREE_STACK_RETURN (REG_BADBR
);
2794 /* We just parsed a valid interval. */
2796 /* If it's invalid to have no preceding re. */
2799 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2800 FREE_STACK_RETURN (REG_BADRPT
);
2801 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2804 goto unfetch_interval
;
2807 if (upper_bound
== 0)
2808 /* If the upper bound is zero, just drop the sub pattern
2811 else if (lower_bound
== 1 && upper_bound
== 1)
2812 /* Just match it once: nothing to do here. */
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 int nbytes
= (upper_bound
< 0 ? 3
2828 : upper_bound
> 1 ? 5 : 0);
2829 unsigned int startoffset
= 0;
2831 GET_BUFFER_SPACE (20); /* We might use less. */
2833 if (lower_bound
== 0)
2835 /* A succeed_n that starts with 0 is really a
2836 a simple on_failure_jump_loop. */
2837 INSERT_JUMP (on_failure_jump_loop
, laststart
,
2843 /* Initialize lower bound of the `succeed_n', even
2844 though it will be set during matching by its
2845 attendant `set_number_at' (inserted next),
2846 because `re_compile_fastmap' needs to know.
2847 Jump to the `jump_n' we might insert below. */
2848 INSERT_JUMP2 (succeed_n
, laststart
,
2853 /* Code to initialize the lower bound. Insert
2854 before the `succeed_n'. The `5' is the last two
2855 bytes of this `set_number_at', plus 3 bytes of
2856 the following `succeed_n'. */
2857 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
2862 if (upper_bound
< 0)
2864 /* A negative upper bound stands for infinity,
2865 in which case it degenerates to a plain jump. */
2866 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2869 else if (upper_bound
> 1)
2870 { /* More than one repetition is allowed, so
2871 append a backward jump to the `succeed_n'
2872 that starts this interval.
2874 When we've reached this during matching,
2875 we'll have matched the interval once, so
2876 jump back only `upper_bound - 1' times. */
2877 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
2881 /* The location we want to set is the second
2882 parameter of the `jump_n'; that is `b-2' as
2883 an absolute address. `laststart' will be
2884 the `set_number_at' we're about to insert;
2885 `laststart+3' the number to set, the source
2886 for the relative address. But we are
2887 inserting into the middle of the pattern --
2888 so everything is getting moved up by 5.
2889 Conclusion: (b - 2) - (laststart + 3) + 5,
2890 i.e., b - laststart.
2892 We insert this at the beginning of the loop
2893 so that if we fail during matching, we'll
2894 reinitialize the bounds. */
2895 insert_op2 (set_number_at
, laststart
, b
- laststart
,
2896 upper_bound
- 1, b
);
2901 beg_interval
= NULL
;
2906 /* If an invalid interval, match the characters as literals. */
2907 assert (beg_interval
);
2909 beg_interval
= NULL
;
2911 /* normal_char and normal_backslash need `c'. */
2914 if (!(syntax
& RE_NO_BK_BRACES
))
2916 assert (p
> pattern
&& p
[-1] == '\\');
2917 goto normal_backslash
;
2923 /* There is no way to specify the before_dot and after_dot
2924 operators. rms says this is ok. --karl */
2932 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2938 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
2944 BUF_PUSH_2 (categoryspec
, c
);
2950 BUF_PUSH_2 (notcategoryspec
, c
);
2957 BUF_PUSH_2 (syntaxspec
, Sword
);
2963 BUF_PUSH_2 (notsyntaxspec
, Sword
);
2976 BUF_PUSH (wordbound
);
2980 BUF_PUSH (notwordbound
);
2991 case '1': case '2': case '3': case '4': case '5':
2992 case '6': case '7': case '8': case '9':
2993 if (syntax
& RE_NO_BK_REFS
)
2999 FREE_STACK_RETURN (REG_ESUBREG
);
3001 /* Can't back reference to a subexpression if inside of it. */
3002 if (group_in_compile_stack (compile_stack
, c1
))
3006 BUF_PUSH_2 (duplicate
, c1
);
3012 if (syntax
& RE_BK_PLUS_QM
)
3015 goto normal_backslash
;
3019 /* You might think it would be useful for \ to mean
3020 not to translate; but if we don't translate it
3021 it will never match anything. */
3029 /* Expects the character in `c'. */
3031 p1
= p
- 1; /* P1 points the head of C. */
3033 if (bufp
->multibyte
)
3035 c
= STRING_CHAR (p1
, pend
- p1
);
3037 /* Set P to the next character boundary. */
3038 p
+= MULTIBYTE_FORM_LENGTH (p1
, pend
- p1
) - 1;
3041 /* If no exactn currently being built. */
3044 /* If last exactn not at current position. */
3045 || pending_exact
+ *pending_exact
+ 1 != b
3047 /* We have only one byte following the exactn for the count. */
3048 || *pending_exact
>= (1 << BYTEWIDTH
) - (p
- p1
)
3050 /* If followed by a repetition operator. */
3051 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3052 || ((syntax
& RE_BK_PLUS_QM
)
3053 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3054 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3055 || ((syntax
& RE_INTERVALS
)
3056 && ((syntax
& RE_NO_BK_BRACES
)
3057 ? p
!= pend
&& *p
== '{'
3058 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3060 /* Start building a new exactn. */
3064 BUF_PUSH_2 (exactn
, 0);
3065 pending_exact
= b
- 1;
3069 if (! SINGLE_BYTE_CHAR_P (c
))
3071 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
3072 int i
= CHAR_STRING (c
, str
);
3074 for (j
= 0; j
< i
; j
++)
3088 } /* while p != pend */
3091 /* Through the pattern now. */
3095 if (!COMPILE_STACK_EMPTY
)
3096 FREE_STACK_RETURN (REG_EPAREN
);
3098 /* If we don't want backtracking, force success
3099 the first time we reach the end of the compiled pattern. */
3100 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3103 free (compile_stack
.stack
);
3105 /* We have succeeded; set the length of the buffer. */
3106 bufp
->used
= b
- bufp
->buffer
;
3111 re_compile_fastmap (bufp
);
3112 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3113 print_compiled_pattern (bufp
);
3118 #ifndef MATCH_MAY_ALLOCATE
3119 /* Initialize the failure stack to the largest possible stack. This
3120 isn't necessary unless we're trying to avoid calling alloca in
3121 the search and match routines. */
3123 int num_regs
= bufp
->re_nsub
+ 1;
3125 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3127 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3129 if (! fail_stack
.stack
)
3131 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3132 * sizeof (fail_stack_elt_t
));
3135 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3137 * sizeof (fail_stack_elt_t
)));
3140 regex_grow_registers (num_regs
);
3142 #endif /* not MATCH_MAY_ALLOCATE */
3145 } /* regex_compile */
3147 /* Subroutines for `regex_compile'. */
3149 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3152 store_op1 (op
, loc
, arg
)
3157 *loc
= (unsigned char) op
;
3158 STORE_NUMBER (loc
+ 1, arg
);
3162 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3165 store_op2 (op
, loc
, arg1
, arg2
)
3170 *loc
= (unsigned char) op
;
3171 STORE_NUMBER (loc
+ 1, arg1
);
3172 STORE_NUMBER (loc
+ 3, arg2
);
3176 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3177 for OP followed by two-byte integer parameter ARG. */
3180 insert_op1 (op
, loc
, arg
, end
)
3186 register unsigned char *pfrom
= end
;
3187 register unsigned char *pto
= end
+ 3;
3189 while (pfrom
!= loc
)
3192 store_op1 (op
, loc
, arg
);
3196 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3199 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3205 register unsigned char *pfrom
= end
;
3206 register unsigned char *pto
= end
+ 5;
3208 while (pfrom
!= loc
)
3211 store_op2 (op
, loc
, arg1
, arg2
);
3215 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3216 after an alternative or a begin-subexpression. We assume there is at
3217 least one character before the ^. */
3220 at_begline_loc_p (pattern
, p
, syntax
)
3221 const unsigned char *pattern
, *p
;
3222 reg_syntax_t syntax
;
3224 const unsigned char *prev
= p
- 2;
3225 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3228 /* After a subexpression? */
3229 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3230 /* After an alternative? */
3231 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
));
3235 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3236 at least one character after the $, i.e., `P < PEND'. */
3239 at_endline_loc_p (p
, pend
, syntax
)
3240 const unsigned char *p
, *pend
;
3241 reg_syntax_t syntax
;
3243 const unsigned char *next
= p
;
3244 boolean next_backslash
= *next
== '\\';
3245 const unsigned char *next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3248 /* Before a subexpression? */
3249 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3250 : next_backslash
&& next_next
&& *next_next
== ')')
3251 /* Before an alternative? */
3252 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3253 : next_backslash
&& next_next
&& *next_next
== '|');
3257 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3258 false if it's not. */
3261 group_in_compile_stack (compile_stack
, regnum
)
3262 compile_stack_type compile_stack
;
3267 for (this_element
= compile_stack
.avail
- 1;
3270 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3277 If fastmap is non-NULL, go through the pattern and fill fastmap
3278 with all the possible leading chars. If fastmap is NULL, don't
3279 bother filling it up (obviously) and only return whether the
3280 pattern could potentially match the empty string.
3282 Return 1 if p..pend might match the empty string.
3283 Return 0 if p..pend matches at least one char.
3284 Return -1 if p..pend matches at least one char, but fastmap was not
3286 Return -2 if an error occurred. */
3289 analyse_first (p
, pend
, fastmap
, multibyte
)
3290 unsigned char *p
, *pend
;
3292 const int multibyte
;
3296 #ifdef MATCH_MAY_ALLOCATE
3297 fail_stack_type fail_stack
;
3299 #ifndef REGEX_MALLOC
3303 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
3304 /* This holds the pointer to the failure stack, when
3305 it is allocated relocatably. */
3306 fail_stack_elt_t
*failure_stack_ptr
;
3309 /* Assume that each path through the pattern can be null until
3310 proven otherwise. We set this false at the bottom of switch
3311 statement, to which we get only if a particular path doesn't
3312 match the empty string. */
3313 boolean path_can_be_null
= true;
3315 /* If all elements for base leading-codes in fastmap is set, this
3316 flag is set true. */
3317 boolean match_any_multibyte_characters
= false;
3323 /* The loop below works as follows:
3324 - It has a working-list kept in the PATTERN_STACK and which basically
3325 starts by only containing a pointer to the first operation.
3326 - If the opcode we're looking at is a match against some set of
3327 chars, then we add those chars to the fastmap and go on to the
3328 next work element from the worklist (done via `break').
3329 - If the opcode is a control operator on the other hand, we either
3330 ignore it (if it's meaningless at this point, such as `start_memory')
3331 or execute it (if it's a jump). If the jump has several destinations
3332 (i.e. `on_failure_jump'), then we push the other destination onto the
3334 We guarantee termination by ignoring backward jumps (more or less),
3335 so that `p' is monotonically increasing. More to the point, we
3336 never set `p' (or push) anything `<= p1'. */
3338 /* If can_be_null is set, then the fastmap will not be used anyway. */
3341 /* `p1' is used as a marker of how far back a `on_failure_jump'
3342 can go without being ignored. It is normally equal to `p'
3343 (which prevents any backward `on_failure_jump') except right
3344 after a plain `jump', to allow patterns such as:
3347 10: on_failure_jump 3
3348 as used for the *? operator. */
3349 unsigned char *p1
= p
;
3353 if (path_can_be_null
)
3354 return (RESET_FAIL_STACK (), 1);
3356 /* We have reached the (effective) end of pattern. */
3357 if (PATTERN_STACK_EMPTY ())
3358 return (RESET_FAIL_STACK (), 0);
3360 p
= (unsigned char*) POP_PATTERN_OP ();
3361 path_can_be_null
= true;
3365 /* We should never be about to go beyond the end of the pattern. */
3368 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3375 /* If the first character has to match a backreference, that means
3376 that the group was empty (since it already matched). Since this
3377 is the only case that interests us here, we can assume that the
3378 backreference must match the empty string. */
3383 /* Following are the cases which match a character. These end
3387 if (fastmap
) fastmap
[p
[1]] = 1;
3392 /* We could put all the chars except for \n (and maybe \0)
3393 but we don't bother since it is generally not worth it. */
3394 if (!fastmap
) break;
3395 return (RESET_FAIL_STACK (), -1);
3399 /* Chars beyond end of bitmap are possible matches.
3400 All the single-byte codes can occur in multibyte buffers.
3401 So any that are not listed in the charset
3402 are possible matches, even in multibyte buffers. */
3403 if (!fastmap
) break;
3404 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3405 j
< (1 << BYTEWIDTH
); j
++)
3409 if (!fastmap
) break;
3410 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3411 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3413 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3416 if ((not && multibyte
)
3417 /* Any character set can possibly contain a character
3418 which doesn't match the specified set of characters. */
3419 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3420 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3421 /* If we can match a character class, we can match
3422 any character set. */
3424 set_fastmap_for_multibyte_characters
:
3425 if (match_any_multibyte_characters
== false)
3427 for (j
= 0x80; j
< 0xA0; j
++) /* XXX */
3428 if (BASE_LEADING_CODE_P (j
))
3430 match_any_multibyte_characters
= true;
3434 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3435 && match_any_multibyte_characters
== false)
3437 /* Set fastmap[I] 1 where I is a base leading code of each
3438 multibyte character in the range table. */
3441 /* Make P points the range table. `+ 2' is to skip flag
3442 bits for a character class. */
3443 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3445 /* Extract the number of ranges in range table into COUNT. */
3446 EXTRACT_NUMBER_AND_INCR (count
, p
);
3447 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3449 /* Extract the start of each range. */
3450 EXTRACT_CHARACTER (c
, p
);
3451 j
= CHAR_CHARSET (c
);
3452 fastmap
[CHARSET_LEADING_CODE_BASE (j
)] = 1;
3459 if (!fastmap
) break;
3461 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3463 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3464 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3468 /* This match depends on text properties. These end with
3469 aborting optimizations. */
3470 return (RESET_FAIL_STACK (), -1);
3473 case notcategoryspec
:
3474 if (!fastmap
) break;
3475 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3477 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3478 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3482 /* Any character set can possibly contain a character
3483 whose category is K (or not). */
3484 goto set_fastmap_for_multibyte_characters
;
3487 /* All cases after this match the empty string. These end with
3507 EXTRACT_NUMBER_AND_INCR (j
, p
);
3509 /* Backward jumps can only go back to code that we've already
3510 visited. `re_compile' should make sure this is true. */
3513 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3515 case on_failure_jump
:
3516 case on_failure_keep_string_jump
:
3517 case on_failure_jump_loop
:
3518 case on_failure_jump_nastyloop
:
3519 case on_failure_jump_smart
:
3525 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3526 to jump back to "just after here". */
3529 case on_failure_jump
:
3530 case on_failure_keep_string_jump
:
3531 case on_failure_jump_nastyloop
:
3532 case on_failure_jump_loop
:
3533 case on_failure_jump_smart
:
3534 EXTRACT_NUMBER_AND_INCR (j
, p
);
3536 ; /* Backward jump to be ignored. */
3537 else if (!PUSH_PATTERN_OP (p
+ j
, fail_stack
))
3538 return (RESET_FAIL_STACK (), -2);
3543 /* This code simply does not properly handle forward jump_n. */
3544 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3546 /* jump_n can either jump or fall through. The (backward) jump
3547 case has already been handled, so we only need to look at the
3548 fallthrough case. */
3552 /* If N == 0, it should be an on_failure_jump_loop instead. */
3553 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3555 /* We only care about one iteration of the loop, so we don't
3556 need to consider the case where this behaves like an
3573 abort (); /* We have listed all the cases. */
3576 /* Getting here means we have found the possible starting
3577 characters for one path of the pattern -- and that the empty
3578 string does not match. We need not follow this path further.
3579 Instead, look at the next alternative (remembered on the
3580 stack), or quit if no more. The test at the top of the loop
3581 does these things. */
3582 path_can_be_null
= false;
3586 return (RESET_FAIL_STACK (), 0);
3587 } /* analyse_first */
3589 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3590 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3591 characters can start a string that matches the pattern. This fastmap
3592 is used by re_search to skip quickly over impossible starting points.
3594 Character codes above (1 << BYTEWIDTH) are not represented in the
3595 fastmap, but the leading codes are represented. Thus, the fastmap
3596 indicates which character sets could start a match.
3598 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3599 area as BUFP->fastmap.
3601 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3604 Returns 0 if we succeed, -2 if an internal error. */
3607 re_compile_fastmap (bufp
)
3608 struct re_pattern_buffer
*bufp
;
3610 char *fastmap
= bufp
->fastmap
;
3613 assert (fastmap
&& bufp
->buffer
);
3615 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3616 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3618 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3619 fastmap
, bufp
->multibyte
);
3622 bufp
->can_be_null
= (analysis
!= 0);
3624 } /* re_compile_fastmap */
3626 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3627 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3628 this memory for recording register information. STARTS and ENDS
3629 must be allocated using the malloc library routine, and must each
3630 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3632 If NUM_REGS == 0, then subsequent matches should allocate their own
3635 Unless this function is called, the first search or match using
3636 PATTERN_BUFFER will allocate its own register data, without
3637 freeing the old data. */
3640 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3641 struct re_pattern_buffer
*bufp
;
3642 struct re_registers
*regs
;
3644 regoff_t
*starts
, *ends
;
3648 bufp
->regs_allocated
= REGS_REALLOCATE
;
3649 regs
->num_regs
= num_regs
;
3650 regs
->start
= starts
;
3655 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3657 regs
->start
= regs
->end
= (regoff_t
*) 0;
3661 /* Searching routines. */
3663 /* Like re_search_2, below, but only one string is specified, and
3664 doesn't let you say where to stop matching. */
3667 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3668 struct re_pattern_buffer
*bufp
;
3670 int size
, startpos
, range
;
3671 struct re_registers
*regs
;
3673 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3677 /* End address of virtual concatenation of string. */
3678 #define STOP_ADDR_VSTRING(P) \
3679 (((P) >= size1 ? string2 + size2 : string1 + size1))
3681 /* Address of POS in the concatenation of virtual string. */
3682 #define POS_ADDR_VSTRING(POS) \
3683 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3685 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3686 virtual concatenation of STRING1 and STRING2, starting first at index
3687 STARTPOS, then at STARTPOS + 1, and so on.
3689 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3691 RANGE is how far to scan while trying to match. RANGE = 0 means try
3692 only at STARTPOS; in general, the last start tried is STARTPOS +
3695 In REGS, return the indices of the virtual concatenation of STRING1
3696 and STRING2 that matched the entire BUFP->buffer and its contained
3699 Do not consider matching one past the index STOP in the virtual
3700 concatenation of STRING1 and STRING2.
3702 We return either the position in the strings at which the match was
3703 found, -1 if no match, or -2 if error (such as failure
3707 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3708 struct re_pattern_buffer
*bufp
;
3709 const char *str1
, *str2
;
3713 struct re_registers
*regs
;
3717 re_char
*string1
= (re_char
*) str1
;
3718 re_char
*string2
= (re_char
*) str2
;
3719 register char *fastmap
= bufp
->fastmap
;
3720 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3721 int total_size
= size1
+ size2
;
3722 int endpos
= startpos
+ range
;
3723 int anchored_start
= 0;
3725 /* Nonzero if we have to concern multibyte character. */
3726 const boolean multibyte
= bufp
->multibyte
;
3728 /* Check for out-of-range STARTPOS. */
3729 if (startpos
< 0 || startpos
> total_size
)
3732 /* Fix up RANGE if it might eventually take us outside
3733 the virtual concatenation of STRING1 and STRING2.
3734 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3736 range
= 0 - startpos
;
3737 else if (endpos
> total_size
)
3738 range
= total_size
- startpos
;
3740 /* If the search isn't to be a backwards one, don't waste time in a
3741 search for a pattern anchored at beginning of buffer. */
3742 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3751 /* In a forward search for something that starts with \=.
3752 don't keep searching past point. */
3753 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3755 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3761 /* Update the fastmap now if not correct already. */
3762 if (fastmap
&& !bufp
->fastmap_accurate
)
3763 if (re_compile_fastmap (bufp
) == -2)
3766 /* See whether the pattern is anchored. */
3767 if (bufp
->buffer
[0] == begline
)
3771 gl_state
.object
= re_match_object
;
3773 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
3775 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
3779 /* Loop through the string, looking for a place to start matching. */
3782 /* If the pattern is anchored,
3783 skip quickly past places we cannot match.
3784 We don't bother to treat startpos == 0 specially
3785 because that case doesn't repeat. */
3786 if (anchored_start
&& startpos
> 0)
3788 if (! (bufp
->newline_anchor
3789 && ((startpos
<= size1
? string1
[startpos
- 1]
3790 : string2
[startpos
- size1
- 1])
3795 /* If a fastmap is supplied, skip quickly over characters that
3796 cannot be the start of a match. If the pattern can match the
3797 null string, however, we don't need to skip characters; we want
3798 the first null string. */
3799 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3801 register re_char
*d
;
3802 register unsigned int buf_ch
;
3804 d
= POS_ADDR_VSTRING (startpos
);
3806 if (range
> 0) /* Searching forwards. */
3808 register int lim
= 0;
3811 if (startpos
< size1
&& startpos
+ range
>= size1
)
3812 lim
= range
- (size1
- startpos
);
3814 /* Written out as an if-else to avoid testing `translate'
3816 if (RE_TRANSLATE_P (translate
))
3823 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3826 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3831 range
-= buf_charlen
;
3836 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3843 while (range
> lim
&& !fastmap
[*d
])
3849 startpos
+= irange
- range
;
3851 else /* Searching backwards. */
3853 buf_ch
= STRING_CHAR (d
, (startpos
>= size1
3854 ? size2
+ size1
- startpos
3855 : size1
- startpos
));
3856 if (RE_TRANSLATE_P (translate
))
3857 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3859 if (! (buf_ch
>= 0400
3860 || fastmap
[buf_ch
]))
3865 /* If can't match the null string, and that's all we have left, fail. */
3866 if (range
>= 0 && startpos
== total_size
&& fastmap
3867 && !bufp
->can_be_null
)
3870 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3871 startpos
, regs
, stop
);
3872 #ifndef REGEX_MALLOC
3889 /* Update STARTPOS to the next character boundary. */
3892 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3893 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
3894 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
3912 /* Update STARTPOS to the previous character boundary. */
3915 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3918 /* Find the head of multibyte form. */
3919 while (!CHAR_HEAD_P (*p
))
3924 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
3941 /* Declarations and macros for re_match_2. */
3943 static int bcmp_translate ();
3945 /* This converts PTR, a pointer into one of the search strings `string1'
3946 and `string2' into an offset from the beginning of that string. */
3947 #define POINTER_TO_OFFSET(ptr) \
3948 (FIRST_STRING_P (ptr) \
3949 ? ((regoff_t) ((ptr) - string1)) \
3950 : ((regoff_t) ((ptr) - string2 + size1)))
3952 /* Call before fetching a character with *d. This switches over to
3953 string2 if necessary. */
3954 #define PREFETCH() \
3957 /* End of string2 => fail. */ \
3958 if (dend == end_match_2) \
3960 /* End of string1 => advance to string2. */ \
3962 dend = end_match_2; \
3966 /* Test if at very beginning or at very end of the virtual concatenation
3967 of `string1' and `string2'. If only one string, it's `string2'. */
3968 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3969 #define AT_STRINGS_END(d) ((d) == end2)
3972 /* Test if D points to a character which is word-constituent. We have
3973 two special cases to check for: if past the end of string1, look at
3974 the first character in string2; and if before the beginning of
3975 string2, look at the last character in string1. */
3976 #define WORDCHAR_P(d) \
3977 (SYNTAX ((d) == end1 ? *string2 \
3978 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3981 /* Disabled due to a compiler bug -- see comment at case wordbound */
3983 /* The comment at case wordbound is following one, but we don't use
3984 AT_WORD_BOUNDARY anymore to support multibyte form.
3986 The DEC Alpha C compiler 3.x generates incorrect code for the
3987 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3988 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3989 macro and introducing temporary variables works around the bug. */
3992 /* Test if the character before D and the one at D differ with respect
3993 to being word-constituent. */
3994 #define AT_WORD_BOUNDARY(d) \
3995 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3996 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3999 /* Free everything we malloc. */
4000 #ifdef MATCH_MAY_ALLOCATE
4001 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4002 #define FREE_VARIABLES() \
4004 REGEX_FREE_STACK (fail_stack.stack); \
4005 FREE_VAR (regstart); \
4006 FREE_VAR (regend); \
4007 FREE_VAR (best_regstart); \
4008 FREE_VAR (best_regend); \
4011 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4012 #endif /* not MATCH_MAY_ALLOCATE */
4015 /* Optimization routines. */
4017 /* If the operation is a match against one or more chars,
4018 return a pointer to the next operation, else return NULL. */
4019 static unsigned char *
4023 switch (SWITCH_ENUM_CAST (*p
++))
4034 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4037 p
= CHARSET_RANGE_TABLE (p
- 1);
4038 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4039 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4042 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4049 case notcategoryspec
:
4061 /* Jump over non-matching operations. */
4062 static unsigned char *
4063 skip_noops (p
, pend
)
4064 unsigned char *p
, *pend
;
4069 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4078 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4089 /* Non-zero if "p1 matches something" implies "p2 fails". */
4091 mutually_exclusive_p (bufp
, p1
, p2
)
4092 struct re_pattern_buffer
*bufp
;
4093 unsigned char *p1
, *p2
;
4096 const boolean multibyte
= bufp
->multibyte
;
4097 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4099 assert (p1
>= bufp
->buffer
&& p1
< pend
4100 && p2
>= bufp
->buffer
&& p2
<= pend
);
4102 /* Skip over open/close-group commands.
4103 If what follows this loop is a ...+ construct,
4104 look at what begins its body, since we will have to
4105 match at least one of that. */
4106 p2
= skip_noops (p2
, pend
);
4107 /* The same skip can be done for p1, except that this function
4108 is only used in the case where p1 is a simple match operator. */
4109 /* p1 = skip_noops (p1, pend); */
4111 assert (p1
>= bufp
->buffer
&& p1
< pend
4112 && p2
>= bufp
->buffer
&& p2
<= pend
);
4114 op2
= p2
== pend
? succeed
: *p2
;
4116 switch (SWITCH_ENUM_CAST (op2
))
4120 /* If we're at the end of the pattern, we can change. */
4121 if (skip_one_char (p1
))
4123 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4129 if (!bufp
->newline_anchor
)
4134 register unsigned int c
4135 = (re_opcode_t
) *p2
== endline
? '\n'
4136 : RE_STRING_CHAR(p2
+ 2, pend
- p2
- 2);
4138 if ((re_opcode_t
) *p1
== exactn
)
4140 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4142 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4147 else if ((re_opcode_t
) *p1
== charset
4148 || (re_opcode_t
) *p1
== charset_not
)
4150 int not = (re_opcode_t
) *p1
== charset_not
;
4152 /* Test if C is listed in charset (or charset_not)
4154 if (SINGLE_BYTE_CHAR_P (c
))
4156 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4157 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4160 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4161 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4163 /* `not' is equal to 1 if c would match, which means
4164 that we can't change to pop_failure_jump. */
4167 DEBUG_PRINT1 (" No match => fast loop.\n");
4171 else if ((re_opcode_t
) *p1
== anychar
4174 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4183 if ((re_opcode_t
) *p1
== exactn
)
4184 /* Reuse the code above. */
4185 return mutually_exclusive_p (bufp
, p2
, p1
);
4188 /* It is hard to list up all the character in charset
4189 P2 if it includes multibyte character. Give up in
4191 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4193 /* Now, we are sure that P2 has no range table.
4194 So, for the size of bitmap in P2, `p2[1]' is
4195 enough. But P1 may have range table, so the
4196 size of bitmap table of P1 is extracted by
4197 using macro `CHARSET_BITMAP_SIZE'.
4199 Since we know that all the character listed in
4200 P2 is ASCII, it is enough to test only bitmap
4206 /* We win if the charset inside the loop
4207 has no overlap with the one after the loop. */
4210 && idx
< CHARSET_BITMAP_SIZE (p1
));
4212 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4216 || idx
== CHARSET_BITMAP_SIZE (p1
))
4218 DEBUG_PRINT1 (" No match => fast loop.\n");
4222 else if ((re_opcode_t
) *p1
== charset
4223 || (re_opcode_t
) *p1
== charset_not
)
4226 /* We win if the charset_not inside the loop lists
4227 every character listed in the charset after. */
4228 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4229 if (! (p2
[2 + idx
] == 0
4230 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4231 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4236 DEBUG_PRINT1 (" No match => fast loop.\n");
4245 return ((re_opcode_t
) *p1
== syntaxspec
4246 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4250 return ((re_opcode_t
) *p1
== notsyntaxspec
4251 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4254 return (((re_opcode_t
) *p1
== notsyntaxspec
4255 || (re_opcode_t
) *p1
== syntaxspec
)
4260 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4261 case notcategoryspec
:
4262 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4274 /* Matching routines. */
4276 #ifndef emacs /* Emacs never uses this. */
4277 /* re_match is like re_match_2 except it takes only a single string. */
4280 re_match (bufp
, string
, size
, pos
, regs
)
4281 struct re_pattern_buffer
*bufp
;
4284 struct re_registers
*regs
;
4286 int result
= re_match_2_internal (bufp
, NULL
, 0, string
, size
,
4291 #endif /* not emacs */
4294 /* In Emacs, this is the string or buffer in which we
4295 are matching. It is used for looking up syntax properties. */
4296 Lisp_Object re_match_object
;
4299 /* re_match_2 matches the compiled pattern in BUFP against the
4300 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4301 and SIZE2, respectively). We start matching at POS, and stop
4304 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4305 store offsets for the substring each group matched in REGS. See the
4306 documentation for exactly how many groups we fill.
4308 We return -1 if no match, -2 if an internal error (such as the
4309 failure stack overflowing). Otherwise, we return the length of the
4310 matched substring. */
4313 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4314 struct re_pattern_buffer
*bufp
;
4315 const char *string1
, *string2
;
4318 struct re_registers
*regs
;
4325 gl_state
.object
= re_match_object
;
4326 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4327 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4330 result
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4336 /* This is a separate function so that we can force an alloca cleanup
4339 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4340 struct re_pattern_buffer
*bufp
;
4341 re_char
*string1
, *string2
;
4344 struct re_registers
*regs
;
4347 /* General temporaries. */
4352 /* Just past the end of the corresponding string. */
4353 re_char
*end1
, *end2
;
4355 /* Pointers into string1 and string2, just past the last characters in
4356 each to consider matching. */
4357 re_char
*end_match_1
, *end_match_2
;
4359 /* Where we are in the data, and the end of the current string. */
4362 /* Used sometimes to remember where we were before starting matching
4363 an operator so that we can go back in case of failure. This "atomic"
4364 behavior of matching opcodes is indispensable to the correctness
4365 of the on_failure_keep_string_jump optimization. */
4368 /* Where we are in the pattern, and the end of the pattern. */
4369 unsigned char *p
= bufp
->buffer
;
4370 register unsigned char *pend
= p
+ bufp
->used
;
4372 /* We use this to map every character in the string. */
4373 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4375 /* Nonzero if we have to concern multibyte character. */
4376 const boolean multibyte
= bufp
->multibyte
;
4378 /* Failure point stack. Each place that can handle a failure further
4379 down the line pushes a failure point on this stack. It consists of
4380 regstart, and regend for all registers corresponding to
4381 the subexpressions we're currently inside, plus the number of such
4382 registers, and, finally, two char *'s. The first char * is where
4383 to resume scanning the pattern; the second one is where to resume
4384 scanning the strings. */
4385 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4386 fail_stack_type fail_stack
;
4389 static unsigned failure_id
= 0;
4390 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4393 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
4394 /* This holds the pointer to the failure stack, when
4395 it is allocated relocatably. */
4396 fail_stack_elt_t
*failure_stack_ptr
;
4399 /* We fill all the registers internally, independent of what we
4400 return, for use in backreferences. The number here includes
4401 an element for register zero. */
4402 unsigned num_regs
= bufp
->re_nsub
+ 1;
4404 /* Information on the contents of registers. These are pointers into
4405 the input strings; they record just what was matched (on this
4406 attempt) by a subexpression part of the pattern, that is, the
4407 regnum-th regstart pointer points to where in the pattern we began
4408 matching and the regnum-th regend points to right after where we
4409 stopped matching the regnum-th subexpression. (The zeroth register
4410 keeps track of what the whole pattern matches.) */
4411 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4412 re_char
**regstart
, **regend
;
4415 /* The following record the register info as found in the above
4416 variables when we find a match better than any we've seen before.
4417 This happens as we backtrack through the failure points, which in
4418 turn happens only if we have not yet matched the entire string. */
4419 unsigned best_regs_set
= false;
4420 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4421 re_char
**best_regstart
, **best_regend
;
4424 /* Logically, this is `best_regend[0]'. But we don't want to have to
4425 allocate space for that if we're not allocating space for anything
4426 else (see below). Also, we never need info about register 0 for
4427 any of the other register vectors, and it seems rather a kludge to
4428 treat `best_regend' differently than the rest. So we keep track of
4429 the end of the best match so far in a separate variable. We
4430 initialize this to NULL so that when we backtrack the first time
4431 and need to test it, it's not garbage. */
4432 re_char
*match_end
= NULL
;
4435 /* Counts the total number of registers pushed. */
4436 unsigned num_regs_pushed
= 0;
4439 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4443 #ifdef MATCH_MAY_ALLOCATE
4444 /* Do not bother to initialize all the register variables if there are
4445 no groups in the pattern, as it takes a fair amount of time. If
4446 there are groups, we include space for register 0 (the whole
4447 pattern), even though we never use it, since it simplifies the
4448 array indexing. We should fix this. */
4451 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4452 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4453 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4454 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4456 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4464 /* We must initialize all our variables to NULL, so that
4465 `FREE_VARIABLES' doesn't try to free them. */
4466 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4468 #endif /* MATCH_MAY_ALLOCATE */
4470 /* The starting position is bogus. */
4471 if (pos
< 0 || pos
> size1
+ size2
)
4477 /* Initialize subexpression text positions to -1 to mark ones that no
4478 start_memory/stop_memory has been seen for. Also initialize the
4479 register information struct. */
4480 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4481 regstart
[mcnt
] = regend
[mcnt
] = REG_UNSET_VALUE
;
4483 /* Shorten strings to `stop'. */
4489 else if (stop
<= size1
+ size2
)
4490 size2
= stop
- size1
;
4492 /* We move `string1' into `string2' if the latter's empty -- but not if
4493 `string1' is null. */
4494 if (size2
== 0 && string1
!= NULL
)
4501 end1
= string1
+ size1
;
4502 end2
= string2
+ size2
;
4504 /* Compute where to stop matching, within the two strings. */
4508 /* `p' scans through the pattern as `d' scans through the data.
4509 `dend' is the end of the input string that `d' points within. `d'
4510 is advanced into the following input string whenever necessary, but
4511 this happens before fetching; therefore, at the beginning of the
4512 loop, `d' can be pointing at the end of a string, but it cannot
4514 if (size1
> 0 && pos
<= size1
)
4521 d
= string2
+ pos
- size1
;
4525 DEBUG_PRINT1 ("The compiled pattern is: ");
4526 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4527 DEBUG_PRINT1 ("The string to match is: `");
4528 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4529 DEBUG_PRINT1 ("'\n");
4531 /* This loops over pattern commands. It exits by returning from the
4532 function if the match is complete, or it drops through if the match
4533 fails at this starting point in the input data. */
4536 DEBUG_PRINT2 ("\n%p: ", p
);
4539 { /* End of pattern means we might have succeeded. */
4540 DEBUG_PRINT1 ("end of pattern ... ");
4542 /* If we haven't matched the entire string, and we want the
4543 longest match, try backtracking. */
4544 if (d
!= end_match_2
)
4546 /* 1 if this match ends in the same string (string1 or string2)
4547 as the best previous match. */
4548 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4549 == FIRST_STRING_P (d
));
4550 /* 1 if this match is the best seen so far. */
4551 boolean best_match_p
;
4553 /* AIX compiler got confused when this was combined
4554 with the previous declaration. */
4556 best_match_p
= d
> match_end
;
4558 best_match_p
= !FIRST_STRING_P (d
);
4560 DEBUG_PRINT1 ("backtracking.\n");
4562 if (!FAIL_STACK_EMPTY ())
4563 { /* More failure points to try. */
4565 /* If exceeds best match so far, save it. */
4566 if (!best_regs_set
|| best_match_p
)
4568 best_regs_set
= true;
4571 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4573 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4575 best_regstart
[mcnt
] = regstart
[mcnt
];
4576 best_regend
[mcnt
] = regend
[mcnt
];
4582 /* If no failure points, don't restore garbage. And if
4583 last match is real best match, don't restore second
4585 else if (best_regs_set
&& !best_match_p
)
4588 /* Restore best match. It may happen that `dend ==
4589 end_match_1' while the restored d is in string2.
4590 For example, the pattern `x.*y.*z' against the
4591 strings `x-' and `y-z-', if the two strings are
4592 not consecutive in memory. */
4593 DEBUG_PRINT1 ("Restoring best registers.\n");
4596 dend
= ((d
>= string1
&& d
<= end1
)
4597 ? end_match_1
: end_match_2
);
4599 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4601 regstart
[mcnt
] = best_regstart
[mcnt
];
4602 regend
[mcnt
] = best_regend
[mcnt
];
4605 } /* d != end_match_2 */
4608 DEBUG_PRINT1 ("Accepting match.\n");
4610 /* If caller wants register contents data back, do it. */
4611 if (regs
&& !bufp
->no_sub
)
4613 /* Have the register data arrays been allocated? */
4614 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4615 { /* No. So allocate them with malloc. We need one
4616 extra element beyond `num_regs' for the `-1' marker
4618 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4619 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4620 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4621 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4626 bufp
->regs_allocated
= REGS_REALLOCATE
;
4628 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4629 { /* Yes. If we need more elements than were already
4630 allocated, reallocate them. If we need fewer, just
4632 if (regs
->num_regs
< num_regs
+ 1)
4634 regs
->num_regs
= num_regs
+ 1;
4635 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4636 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4637 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4646 /* These braces fend off a "empty body in an else-statement"
4647 warning under GCC when assert expands to nothing. */
4648 assert (bufp
->regs_allocated
== REGS_FIXED
);
4651 /* Convert the pointer data in `regstart' and `regend' to
4652 indices. Register zero has to be set differently,
4653 since we haven't kept track of any info for it. */
4654 if (regs
->num_regs
> 0)
4656 regs
->start
[0] = pos
;
4657 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4660 /* Go through the first `min (num_regs, regs->num_regs)'
4661 registers, since that is all we initialized. */
4662 for (mcnt
= 1; mcnt
< MIN (num_regs
, regs
->num_regs
); mcnt
++)
4664 if (REG_UNSET (regstart
[mcnt
]) || REG_UNSET (regend
[mcnt
]))
4665 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4669 = (regoff_t
) POINTER_TO_OFFSET (regstart
[mcnt
]);
4671 = (regoff_t
) POINTER_TO_OFFSET (regend
[mcnt
]);
4675 /* If the regs structure we return has more elements than
4676 were in the pattern, set the extra elements to -1. If
4677 we (re)allocated the registers, this is the case,
4678 because we always allocate enough to have at least one
4680 for (mcnt
= num_regs
; mcnt
< regs
->num_regs
; mcnt
++)
4681 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4682 } /* regs && !bufp->no_sub */
4684 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4685 nfailure_points_pushed
, nfailure_points_popped
,
4686 nfailure_points_pushed
- nfailure_points_popped
);
4687 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4689 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4691 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4697 /* Otherwise match next pattern command. */
4698 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4700 /* Ignore these. Used to ignore the n of succeed_n's which
4701 currently have n == 0. */
4703 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4707 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4710 /* Match the next n pattern characters exactly. The following
4711 byte in the pattern defines n, and the n bytes after that
4712 are the characters to match. */
4715 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4717 /* Remember the start point to rollback upon failure. */
4720 /* This is written out as an if-else so we don't waste time
4721 testing `translate' inside the loop. */
4722 if (RE_TRANSLATE_P (translate
))
4728 int pat_charlen
, buf_charlen
;
4729 unsigned int pat_ch
, buf_ch
;
4732 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
4733 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4735 if (RE_TRANSLATE (translate
, buf_ch
)
4744 mcnt
-= pat_charlen
;
4748 #endif /* not emacs */
4752 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4777 /* Match any character except possibly a newline or a null. */
4781 unsigned int buf_ch
;
4783 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4789 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4791 #endif /* not emacs */
4797 buf_ch
= TRANSLATE (buf_ch
);
4799 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4801 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4802 && buf_ch
== '\000'))
4805 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4814 register unsigned int c
;
4815 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4818 /* Start of actual range_table, or end of bitmap if there is no
4820 unsigned char *range_table
;
4822 /* Nonzero if there is a range table. */
4823 int range_table_exists
;
4825 /* Number of ranges of range table. This is not included
4826 in the initial byte-length of the command. */
4829 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4834 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
4837 if (range_table_exists
)
4839 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
4840 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
4843 if (multibyte
&& BASE_LEADING_CODE_P (c
))
4844 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
4847 if (SINGLE_BYTE_CHAR_P (c
))
4848 { /* Lookup bitmap. */
4849 c
= TRANSLATE (c
); /* The character to match. */
4852 /* Cast to `unsigned' instead of `unsigned char' in
4853 case the bit list is a full 32 bytes long. */
4854 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
4855 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4859 else if (range_table_exists
)
4861 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
4863 if ( (class_bits
& BIT_ALNUM
&& ISALNUM (c
))
4864 | (class_bits
& BIT_ALPHA
&& ISALPHA (c
))
4865 | (class_bits
& BIT_ASCII
&& IS_REAL_ASCII (c
))
4866 | (class_bits
& BIT_GRAPH
&& ISGRAPH (c
))
4867 | (class_bits
& BIT_LOWER
&& ISLOWER (c
))
4868 | (class_bits
& BIT_MULTIBYTE
&& !ISUNIBYTE (c
))
4869 | (class_bits
& BIT_NONASCII
&& !IS_REAL_ASCII (c
))
4870 | (class_bits
& BIT_PRINT
&& ISPRINT (c
))
4871 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
4872 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
4873 | (class_bits
& BIT_UNIBYTE
&& ISUNIBYTE (c
))
4874 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
4875 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
4878 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
4882 if (range_table_exists
)
4883 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
4885 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
4887 if (!not) goto fail
;
4894 /* The beginning of a group is represented by start_memory.
4895 The argument is the register number. The text
4896 matched within the group is recorded (in the internal
4897 registers data structure) under the register number. */
4899 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
4901 /* In case we need to undo this operation (via backtracking). */
4902 PUSH_FAILURE_REG ((unsigned int)*p
);
4905 regend
[*p
] = REG_UNSET_VALUE
; /* probably unnecessary. -sm */
4906 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
4908 /* Move past the register number and inner group count. */
4913 /* The stop_memory opcode represents the end of a group. Its
4914 argument is the same as start_memory's: the register number. */
4916 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
4918 assert (!REG_UNSET (regstart
[*p
]));
4919 /* Strictly speaking, there should be code such as:
4921 assert (REG_UNSET (regend[*p]));
4922 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
4924 But the only info to be pushed is regend[*p] and it is known to
4925 be UNSET, so there really isn't anything to push.
4926 Not pushing anything, on the other hand deprives us from the
4927 guarantee that regend[*p] is UNSET since undoing this operation
4928 will not reset its value properly. This is not important since
4929 the value will only be read on the next start_memory or at
4930 the very end and both events can only happen if this stop_memory
4934 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
4936 /* Move past the register number and the inner group count. */
4941 /* \<digit> has been turned into a `duplicate' command which is
4942 followed by the numeric value of <digit> as the register number. */
4945 register re_char
*d2
, *dend2
;
4946 int regno
= *p
++; /* Get which register to match against. */
4947 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
4949 /* Can't back reference a group which we've never matched. */
4950 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
4953 /* Where in input to try to start matching. */
4954 d2
= regstart
[regno
];
4956 /* Remember the start point to rollback upon failure. */
4959 /* Where to stop matching; if both the place to start and
4960 the place to stop matching are in the same string, then
4961 set to the place to stop, otherwise, for now have to use
4962 the end of the first string. */
4964 dend2
= ((FIRST_STRING_P (regstart
[regno
])
4965 == FIRST_STRING_P (regend
[regno
]))
4966 ? regend
[regno
] : end_match_1
);
4969 /* If necessary, advance to next segment in register
4973 if (dend2
== end_match_2
) break;
4974 if (dend2
== regend
[regno
]) break;
4976 /* End of string1 => advance to string2. */
4978 dend2
= regend
[regno
];
4980 /* At end of register contents => success */
4981 if (d2
== dend2
) break;
4983 /* If necessary, advance to next segment in data. */
4986 /* How many characters left in this segment to match. */
4989 /* Want how many consecutive characters we can match in
4990 one shot, so, if necessary, adjust the count. */
4991 if (mcnt
> dend2
- d2
)
4994 /* Compare that many; failure if mismatch, else move
4996 if (RE_TRANSLATE_P (translate
)
4997 ? bcmp_translate (d
, d2
, mcnt
, translate
)
4998 : bcmp (d
, d2
, mcnt
))
5003 d
+= mcnt
, d2
+= mcnt
;
5009 /* begline matches the empty string at the beginning of the string
5010 (unless `not_bol' is set in `bufp'), and, if
5011 `newline_anchor' is set, after newlines. */
5013 DEBUG_PRINT1 ("EXECUTING begline.\n");
5015 if (AT_STRINGS_BEG (d
))
5017 if (!bufp
->not_bol
) break;
5019 else if (d
[-1] == '\n' && bufp
->newline_anchor
)
5023 /* In all other cases, we fail. */
5027 /* endline is the dual of begline. */
5029 DEBUG_PRINT1 ("EXECUTING endline.\n");
5031 if (AT_STRINGS_END (d
))
5033 if (!bufp
->not_eol
) break;
5036 /* We have to ``prefetch'' the next character. */
5037 else if ((d
== end1
? *string2
: *d
) == '\n'
5038 && bufp
->newline_anchor
)
5045 /* Match at the very beginning of the data. */
5047 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5048 if (AT_STRINGS_BEG (d
))
5053 /* Match at the very end of the data. */
5055 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5056 if (AT_STRINGS_END (d
))
5061 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5062 pushes NULL as the value for the string on the stack. Then
5063 `POP_FAILURE_POINT' will keep the current value for the
5064 string, instead of restoring it. To see why, consider
5065 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5066 then the . fails against the \n. But the next thing we want
5067 to do is match the \n against the \n; if we restored the
5068 string value, we would be back at the foo.
5070 Because this is used only in specific cases, we don't need to
5071 check all the things that `on_failure_jump' does, to make
5072 sure the right things get saved on the stack. Hence we don't
5073 share its code. The only reason to push anything on the
5074 stack at all is that otherwise we would have to change
5075 `anychar's code to do something besides goto fail in this
5076 case; that seems worse than this. */
5077 case on_failure_keep_string_jump
:
5078 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5079 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5082 PUSH_FAILURE_POINT (p
- 3, NULL
);
5085 /* A nasty loop is introduced by the non-greedy *? and +?.
5086 With such loops, the stack only ever contains one failure point
5087 at a time, so that a plain on_failure_jump_loop kind of
5088 cycle detection cannot work. Worse yet, such a detection
5089 can not only fail to detect a cycle, but it can also wrongly
5090 detect a cycle (between different instantiations of the same
5092 So the method used for those nasty loops is a little different:
5093 We use a special cycle-detection-stack-frame which is pushed
5094 when the on_failure_jump_nastyloop failure-point is *popped*.
5095 This special frame thus marks the beginning of one iteration
5096 through the loop and we can hence easily check right here
5097 whether something matched between the beginning and the end of
5099 case on_failure_jump_nastyloop
:
5100 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5101 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5104 assert ((re_opcode_t
)p
[-4] == no_op
);
5105 CHECK_INFINITE_LOOP (p
- 4, d
);
5106 PUSH_FAILURE_POINT (p
- 3, d
);
5110 /* Simple loop detecting on_failure_jump: just check on the
5111 failure stack if the same spot was already hit earlier. */
5112 case on_failure_jump_loop
:
5114 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5115 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5118 CHECK_INFINITE_LOOP (p
- 3, d
);
5119 PUSH_FAILURE_POINT (p
- 3, d
);
5123 /* Uses of on_failure_jump:
5125 Each alternative starts with an on_failure_jump that points
5126 to the beginning of the next alternative. Each alternative
5127 except the last ends with a jump that in effect jumps past
5128 the rest of the alternatives. (They really jump to the
5129 ending jump of the following alternative, because tensioning
5130 these jumps is a hassle.)
5132 Repeats start with an on_failure_jump that points past both
5133 the repetition text and either the following jump or
5134 pop_failure_jump back to this on_failure_jump. */
5135 case on_failure_jump
:
5137 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5138 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5141 PUSH_FAILURE_POINT (p
-3, d
);
5144 /* This operation is used for greedy *.
5145 Compare the beginning of the repeat with what in the
5146 pattern follows its end. If we can establish that there
5147 is nothing that they would both match, i.e., that we
5148 would have to backtrack because of (as in, e.g., `a*a')
5149 then we can use a non-backtracking loop based on
5150 on_failure_keep_string_jump instead of on_failure_jump. */
5151 case on_failure_jump_smart
:
5153 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5154 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5157 unsigned char *p1
= p
; /* Next operation. */
5158 unsigned char *p2
= p
+ mcnt
; /* Destination of the jump. */
5160 p
-= 3; /* Reset so that we will re-execute the
5161 instruction once it's been changed. */
5163 EXTRACT_NUMBER (mcnt
, p2
- 2);
5165 /* Ensure this is a indeed the trivial kind of loop
5166 we are expecting. */
5167 assert (skip_one_char (p1
) == p2
- 3);
5168 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5169 DEBUG_STATEMENT (debug
+= 2);
5170 if (mutually_exclusive_p (bufp
, p1
, p2
))
5172 /* Use a fast `on_failure_keep_string_jump' loop. */
5173 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5174 *p
= (unsigned char) on_failure_keep_string_jump
;
5175 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5179 /* Default to a safe `on_failure_jump' loop. */
5180 DEBUG_PRINT1 (" smart default => slow loop.\n");
5181 *p
= (unsigned char) on_failure_jump
;
5183 DEBUG_STATEMENT (debug
-= 2);
5187 /* Unconditionally jump (without popping any failure points). */
5191 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5192 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5193 p
+= mcnt
; /* Do the jump. */
5194 DEBUG_PRINT2 ("(to %p).\n", p
);
5198 /* Have to succeed matching what follows at least n times.
5199 After that, handle like `on_failure_jump'. */
5201 EXTRACT_NUMBER (mcnt
, p
+ 2);
5202 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5205 /* Originally, this is how many times we HAVE to succeed. */
5210 STORE_NUMBER_AND_INCR (p
, mcnt
);
5211 DEBUG_PRINT3 (" Setting %p to %d.\n", p
, mcnt
);
5215 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p
+2);
5216 p
[2] = (unsigned char) no_op
;
5217 p
[3] = (unsigned char) no_op
;
5223 EXTRACT_NUMBER (mcnt
, p
+ 2);
5224 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5226 /* Originally, this is how many times we CAN jump. */
5230 STORE_NUMBER (p
+ 2, mcnt
);
5231 goto unconditional_jump
;
5233 /* If don't have to jump any more, skip over the rest of command. */
5240 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5242 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5244 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5245 DEBUG_PRINT3 (" Setting %p to %d.\n", p1
, mcnt
);
5246 STORE_NUMBER (p1
, mcnt
);
5252 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5253 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5255 /* We SUCCEED (or FAIL) in one of the following cases: */
5257 /* Case 1: D is at the beginning or the end of string. */
5258 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5262 /* C1 is the character before D, S1 is the syntax of C1, C2
5263 is the character at D, and S2 is the syntax of C2. */
5266 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
- 1));
5267 UPDATE_SYNTAX_TABLE (charpos
);
5269 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5270 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5273 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5276 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5277 c2
= STRING_CHAR (d
, dend
- d
);
5280 if (/* Case 2: Only one of S1 and S2 is Sword. */
5281 ((s1
== Sword
) != (s2
== Sword
))
5282 /* Case 3: Both of S1 and S2 are Sword, and macro
5283 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5284 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5293 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5295 /* We FAIL in one of the following cases: */
5297 /* Case 1: D is at the end of string. */
5298 if (AT_STRINGS_END (d
))
5302 /* C1 is the character before D, S1 is the syntax of C1, C2
5303 is the character at D, and S2 is the syntax of C2. */
5306 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
));
5307 UPDATE_SYNTAX_TABLE (charpos
);
5310 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5311 c2
= STRING_CHAR (d
, dend
- d
);
5314 /* Case 2: S2 is not Sword. */
5318 /* Case 3: D is not at the beginning of string ... */
5319 if (!AT_STRINGS_BEG (d
))
5321 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5323 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5327 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5329 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5336 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5338 /* We FAIL in one of the following cases: */
5340 /* Case 1: D is at the beginning of string. */
5341 if (AT_STRINGS_BEG (d
))
5345 /* C1 is the character before D, S1 is the syntax of C1, C2
5346 is the character at D, and S2 is the syntax of C2. */
5349 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
) - 1);
5350 UPDATE_SYNTAX_TABLE (charpos
);
5352 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5355 /* Case 2: S1 is not Sword. */
5359 /* Case 3: D is not at the end of string ... */
5360 if (!AT_STRINGS_END (d
))
5363 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5364 c2
= STRING_CHAR (d
, dend
- d
);
5366 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5370 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5372 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5380 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5382 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5386 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d
));
5387 UPDATE_SYNTAX_TABLE (pos1
);
5394 /* we must concern about multibyte form, ... */
5395 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5397 /* everything should be handled as ASCII, even though it
5398 looks like multibyte form. */
5401 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5409 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5410 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5415 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5416 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5421 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5422 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5427 case notcategoryspec
:
5428 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5430 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5436 c
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5440 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5451 continue; /* Successfully executed one pattern command; keep going. */
5454 /* We goto here if a matching operation fails. */
5457 if (!FAIL_STACK_EMPTY ())
5461 /* A restart point is known. Restore to that state. */
5462 DEBUG_PRINT1 ("\nFAIL:\n");
5463 POP_FAILURE_POINT (str
, pat
);
5464 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5466 case on_failure_keep_string_jump
:
5467 assert (str
== NULL
);
5468 goto continue_failure_jump
;
5470 case on_failure_jump_nastyloop
:
5471 assert ((re_opcode_t
)pat
[-2] == no_op
);
5472 PUSH_FAILURE_POINT (pat
- 2, str
);
5475 case on_failure_jump_loop
:
5476 case on_failure_jump
:
5479 continue_failure_jump
:
5480 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5485 /* A special frame used for nastyloops. */
5492 assert (p
>= bufp
->buffer
&& p
<= pend
);
5494 if (d
>= string1
&& d
<= end1
)
5498 break; /* Matching at this starting point really fails. */
5502 goto restore_best_regs
;
5506 return -1; /* Failure to match. */
5509 /* Subroutine definitions for re_match_2. */
5511 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5512 bytes; nonzero otherwise. */
5515 bcmp_translate (s1
, s2
, len
, translate
)
5516 unsigned char *s1
, *s2
;
5518 RE_TRANSLATE_TYPE translate
;
5520 register unsigned char *p1
= s1
, *p2
= s2
;
5521 unsigned char *p1_end
= s1
+ len
;
5522 unsigned char *p2_end
= s2
+ len
;
5524 while (p1
!= p1_end
&& p2
!= p2_end
)
5526 int p1_charlen
, p2_charlen
;
5529 /* FIXME: This assumes `multibyte = true'. */
5530 p1_ch
= STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5531 p2_ch
= STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5533 if (RE_TRANSLATE (translate
, p1_ch
)
5534 != RE_TRANSLATE (translate
, p2_ch
))
5537 p1
+= p1_charlen
, p2
+= p2_charlen
;
5540 if (p1
!= p1_end
|| p2
!= p2_end
)
5546 /* Entry points for GNU code. */
5548 /* re_compile_pattern is the GNU regular expression compiler: it
5549 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5550 Returns 0 if the pattern was valid, otherwise an error string.
5552 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5553 are set in BUFP on entry.
5555 We call regex_compile to do the actual compilation. */
5558 re_compile_pattern (pattern
, length
, bufp
)
5559 const char *pattern
;
5561 struct re_pattern_buffer
*bufp
;
5565 /* GNU code is written to assume at least RE_NREGS registers will be set
5566 (and at least one extra will be -1). */
5567 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5569 /* And GNU code determines whether or not to get register information
5570 by passing null for the REGS argument to re_match, etc., not by
5574 /* Match anchors at newline. */
5575 bufp
->newline_anchor
= 1;
5577 ret
= regex_compile (pattern
, length
, re_syntax_options
, bufp
);
5581 return gettext (re_error_msgid
[(int) ret
]);
5584 /* Entry points compatible with 4.2 BSD regex library. We don't define
5585 them unless specifically requested. */
5587 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5589 /* BSD has one and only one pattern buffer. */
5590 static struct re_pattern_buffer re_comp_buf
;
5594 /* Make these definitions weak in libc, so POSIX programs can redefine
5595 these names if they don't use our functions, and still use
5596 regcomp/regexec below without link errors. */
5606 if (!re_comp_buf
.buffer
)
5607 return gettext ("No previous regular expression");
5611 if (!re_comp_buf
.buffer
)
5613 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5614 if (re_comp_buf
.buffer
== NULL
)
5615 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5616 re_comp_buf
.allocated
= 200;
5618 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5619 if (re_comp_buf
.fastmap
== NULL
)
5620 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5623 /* Since `re_exec' always passes NULL for the `regs' argument, we
5624 don't need to initialize the pattern buffer fields which affect it. */
5626 /* Match anchors at newlines. */
5627 re_comp_buf
.newline_anchor
= 1;
5629 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5634 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5635 return (char *) gettext (re_error_msgid
[(int) ret
]);
5646 const int len
= strlen (s
);
5648 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5650 #endif /* _REGEX_RE_COMP */
5652 /* POSIX.2 functions. Don't define these for Emacs. */
5656 /* regcomp takes a regular expression as a string and compiles it.
5658 PREG is a regex_t *. We do not expect any fields to be initialized,
5659 since POSIX says we shouldn't. Thus, we set
5661 `buffer' to the compiled pattern;
5662 `used' to the length of the compiled pattern;
5663 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5664 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5665 RE_SYNTAX_POSIX_BASIC;
5666 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5667 `fastmap' and `fastmap_accurate' to zero;
5668 `re_nsub' to the number of subexpressions in PATTERN.
5670 PATTERN is the address of the pattern string.
5672 CFLAGS is a series of bits which affect compilation.
5674 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5675 use POSIX basic syntax.
5677 If REG_NEWLINE is set, then . and [^...] don't match newline.
5678 Also, regexec will try a match beginning after every newline.
5680 If REG_ICASE is set, then we considers upper- and lowercase
5681 versions of letters to be equivalent when matching.
5683 If REG_NOSUB is set, then when PREG is passed to regexec, that
5684 routine will report only success or failure, and nothing about the
5687 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5688 the return codes and their meanings.) */
5691 regcomp (preg
, pattern
, cflags
)
5693 const char *pattern
;
5698 = (cflags
& REG_EXTENDED
) ?
5699 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5701 /* regex_compile will allocate the space for the compiled pattern. */
5703 preg
->allocated
= 0;
5706 /* Don't bother to use a fastmap when searching. This simplifies the
5707 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5708 characters after newlines into the fastmap. This way, we just try
5712 if (cflags
& REG_ICASE
)
5717 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5718 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5719 if (preg
->translate
== NULL
)
5720 return (int) REG_ESPACE
;
5722 /* Map uppercase characters to corresponding lowercase ones. */
5723 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5724 preg
->translate
[i
] = ISUPPER (i
) ? tolower (i
) : i
;
5727 preg
->translate
= NULL
;
5729 /* If REG_NEWLINE is set, newlines are treated differently. */
5730 if (cflags
& REG_NEWLINE
)
5731 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5732 syntax
&= ~RE_DOT_NEWLINE
;
5733 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5734 /* It also changes the matching behavior. */
5735 preg
->newline_anchor
= 1;
5738 preg
->newline_anchor
= 0;
5740 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5742 /* POSIX says a null character in the pattern terminates it, so we
5743 can use strlen here in compiling the pattern. */
5744 ret
= regex_compile (pattern
, strlen (pattern
), syntax
, preg
);
5746 /* POSIX doesn't distinguish between an unmatched open-group and an
5747 unmatched close-group: both are REG_EPAREN. */
5748 if (ret
== REG_ERPAREN
) ret
= REG_EPAREN
;
5754 /* regexec searches for a given pattern, specified by PREG, in the
5757 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5758 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5759 least NMATCH elements, and we set them to the offsets of the
5760 corresponding matched substrings.
5762 EFLAGS specifies `execution flags' which affect matching: if
5763 REG_NOTBOL is set, then ^ does not match at the beginning of the
5764 string; if REG_NOTEOL is set, then $ does not match at the end.
5766 We return 0 if we find a match and REG_NOMATCH if not. */
5769 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5770 const regex_t
*preg
;
5773 regmatch_t pmatch
[];
5777 struct re_registers regs
;
5778 regex_t private_preg
;
5779 int len
= strlen (string
);
5780 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
5782 private_preg
= *preg
;
5784 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5785 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5787 /* The user has told us exactly how many registers to return
5788 information about, via `nmatch'. We have to pass that on to the
5789 matching routines. */
5790 private_preg
.regs_allocated
= REGS_FIXED
;
5794 regs
.num_regs
= nmatch
;
5795 regs
.start
= TALLOC (nmatch
, regoff_t
);
5796 regs
.end
= TALLOC (nmatch
, regoff_t
);
5797 if (regs
.start
== NULL
|| regs
.end
== NULL
)
5798 return (int) REG_NOMATCH
;
5801 /* Perform the searching operation. */
5802 ret
= re_search (&private_preg
, string
, len
,
5803 /* start: */ 0, /* range: */ len
,
5804 want_reg_info
? ®s
: (struct re_registers
*) 0);
5806 /* Copy the register information to the POSIX structure. */
5813 for (r
= 0; r
< nmatch
; r
++)
5815 pmatch
[r
].rm_so
= regs
.start
[r
];
5816 pmatch
[r
].rm_eo
= regs
.end
[r
];
5820 /* If we needed the temporary register info, free the space now. */
5825 /* We want zero return to mean success, unlike `re_search'. */
5826 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5830 /* Returns a message corresponding to an error code, ERRCODE, returned
5831 from either regcomp or regexec. We don't use PREG here. */
5834 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5836 const regex_t
*preg
;
5844 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
5845 /* Only error codes returned by the rest of the code should be passed
5846 to this routine. If we are given anything else, or if other regex
5847 code generates an invalid error code, then the program has a bug.
5848 Dump core so we can fix it. */
5851 msg
= gettext (re_error_msgid
[errcode
]);
5853 msg_size
= strlen (msg
) + 1; /* Includes the null. */
5855 if (errbuf_size
!= 0)
5857 if (msg_size
> errbuf_size
)
5859 strncpy (errbuf
, msg
, errbuf_size
- 1);
5860 errbuf
[errbuf_size
- 1] = 0;
5863 strcpy (errbuf
, msg
);
5870 /* Free dynamically allocated space used by PREG. */
5876 if (preg
->buffer
!= NULL
)
5877 free (preg
->buffer
);
5878 preg
->buffer
= NULL
;
5880 preg
->allocated
= 0;
5883 if (preg
->fastmap
!= NULL
)
5884 free (preg
->fastmap
);
5885 preg
->fastmap
= NULL
;
5886 preg
->fastmap_accurate
= 0;
5888 if (preg
->translate
!= NULL
)
5889 free (preg
->translate
);
5890 preg
->translate
= NULL
;
5893 #endif /* not emacs */