Clean up some white spaces, mainly in my own change log entries. (rost)
[emacs.git] / src / regex.c
blob5cb997336f600f005e4b6d827e76913863884fde
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993,94,95,96,97,98,99,2000 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20 USA. */
22 /* TODO:
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
33 #pragma alloca
34 #endif
36 #ifdef HAVE_CONFIG_H
37 # include <config.h>
38 #endif
40 #if defined STDC_HEADERS && !defined emacs
41 # include <stddef.h>
42 #else
43 /* We need this for `regex.h', and perhaps for the Emacs include files. */
44 # include <sys/types.h>
45 #endif
47 /* Whether to use ISO C Amendment 1 wide char functions.
48 Those should not be used for Emacs since it uses its own. */
49 #if defined _LIBC
50 #define WIDE_CHAR_SUPPORT 1
51 #else
52 #define WIDE_CHAR_SUPPORT \
53 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
54 #endif
56 /* For platform which support the ISO C amendement 1 functionality we
57 support user defined character classes. */
58 #if WIDE_CHAR_SUPPORT
59 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
60 # include <wchar.h>
61 # include <wctype.h>
62 #endif
64 #ifdef _LIBC
65 /* We have to keep the namespace clean. */
66 # define regfree(preg) __regfree (preg)
67 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
68 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
69 # define regerror(errcode, preg, errbuf, errbuf_size) \
70 __regerror(errcode, preg, errbuf, errbuf_size)
71 # define re_set_registers(bu, re, nu, st, en) \
72 __re_set_registers (bu, re, nu, st, en)
73 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
74 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
75 # define re_match(bufp, string, size, pos, regs) \
76 __re_match (bufp, string, size, pos, regs)
77 # define re_search(bufp, string, size, startpos, range, regs) \
78 __re_search (bufp, string, size, startpos, range, regs)
79 # define re_compile_pattern(pattern, length, bufp) \
80 __re_compile_pattern (pattern, length, bufp)
81 # define re_set_syntax(syntax) __re_set_syntax (syntax)
82 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
83 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
84 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
86 /* Make sure we call libc's function even if the user overrides them. */
87 # define btowc __btowc
88 # define iswctype __iswctype
89 # define wctype __wctype
91 # define WEAK_ALIAS(a,b) weak_alias (a, b)
93 /* We are also using some library internals. */
94 # include <locale/localeinfo.h>
95 # include <locale/elem-hash.h>
96 # include <langinfo.h>
97 #else
98 # define WEAK_ALIAS(a,b)
99 #endif
101 /* This is for other GNU distributions with internationalized messages. */
102 #if HAVE_LIBINTL_H || defined _LIBC
103 # include <libintl.h>
104 #else
105 # define gettext(msgid) (msgid)
106 #endif
108 #ifndef gettext_noop
109 /* This define is so xgettext can find the internationalizable
110 strings. */
111 # define gettext_noop(String) String
112 #endif
114 /* The `emacs' switch turns on certain matching commands
115 that make sense only in Emacs. */
116 #ifdef emacs
118 # include "lisp.h"
119 # include "buffer.h"
121 /* Make syntax table lookup grant data in gl_state. */
122 # define SYNTAX_ENTRY_VIA_PROPERTY
124 # include "syntax.h"
125 # include "charset.h"
126 # include "category.h"
128 # ifdef malloc
129 # undef malloc
130 # endif
131 # define malloc xmalloc
132 # ifdef realloc
133 # undef realloc
134 # endif
135 # define realloc xrealloc
136 # ifdef free
137 # undef free
138 # endif
139 # define free xfree
141 /* Converts the pointer to the char to BEG-based offset from the start. */
142 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
143 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
145 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
146 # define RE_STRING_CHAR(p, s) \
147 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
148 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
149 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
151 /* Set C a (possibly multibyte) character before P. P points into a
152 string which is the virtual concatenation of STR1 (which ends at
153 END1) or STR2 (which ends at END2). */
154 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
155 do { \
156 if (multibyte) \
158 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
159 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
160 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
161 c = STRING_CHAR (dtemp, (p) - dtemp); \
163 else \
164 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
165 } while (0)
168 #else /* not emacs */
170 /* If we are not linking with Emacs proper,
171 we can't use the relocating allocator
172 even if config.h says that we can. */
173 # undef REL_ALLOC
175 # if defined STDC_HEADERS || defined _LIBC
176 # include <stdlib.h>
177 # else
178 char *malloc ();
179 char *realloc ();
180 # endif
182 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
183 If nothing else has been done, use the method below. */
184 # ifdef INHIBIT_STRING_HEADER
185 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
186 # if !defined bzero && !defined bcopy
187 # undef INHIBIT_STRING_HEADER
188 # endif
189 # endif
190 # endif
192 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
193 This is used in most programs--a few other programs avoid this
194 by defining INHIBIT_STRING_HEADER. */
195 # ifndef INHIBIT_STRING_HEADER
196 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
197 # include <string.h>
198 # ifndef bzero
199 # ifndef _LIBC
200 # define bzero(s, n) (memset (s, '\0', n), (s))
201 # else
202 # define bzero(s, n) __bzero (s, n)
203 # endif
204 # endif
205 # else
206 # include <strings.h>
207 # ifndef memcmp
208 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
209 # endif
210 # ifndef memcpy
211 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
212 # endif
213 # endif
214 # endif
216 /* Define the syntax stuff for \<, \>, etc. */
218 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
219 enum syntaxcode { Swhitespace = 0, Sword = 1 };
221 # ifdef SWITCH_ENUM_BUG
222 # define SWITCH_ENUM_CAST(x) ((int)(x))
223 # else
224 # define SWITCH_ENUM_CAST(x) (x)
225 # endif
227 /* Dummy macros for non-Emacs environments. */
228 # define BASE_LEADING_CODE_P(c) (0)
229 # define CHAR_CHARSET(c) 0
230 # define CHARSET_LEADING_CODE_BASE(c) 0
231 # define MAX_MULTIBYTE_LENGTH 1
232 # define RE_MULTIBYTE_P(x) 0
233 # define WORD_BOUNDARY_P(c1, c2) (0)
234 # define CHAR_HEAD_P(p) (1)
235 # define SINGLE_BYTE_CHAR_P(c) (1)
236 # define SAME_CHARSET_P(c1, c2) (1)
237 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
238 # define STRING_CHAR(p, s) (*(p))
239 # define RE_STRING_CHAR STRING_CHAR
240 # define CHAR_STRING(c, s) (*(s) = (c), 1)
241 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
242 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
243 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
244 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
245 # define MAKE_CHAR(charset, c1, c2) (c1)
246 #endif /* not emacs */
248 #ifndef RE_TRANSLATE
249 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
250 # define RE_TRANSLATE_P(TBL) (TBL)
251 #endif
253 /* Get the interface, including the syntax bits. */
254 #include "regex.h"
256 /* isalpha etc. are used for the character classes. */
257 #include <ctype.h>
259 #ifdef emacs
261 /* 1 if C is an ASCII character. */
262 # define IS_REAL_ASCII(c) ((c) < 0200)
264 /* 1 if C is a unibyte character. */
265 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
267 /* The Emacs definitions should not be directly affected by locales. */
269 /* In Emacs, these are only used for single-byte characters. */
270 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
271 # define ISCNTRL(c) ((c) < ' ')
272 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
273 || ((c) >= 'a' && (c) <= 'f') \
274 || ((c) >= 'A' && (c) <= 'F'))
276 /* This is only used for single-byte characters. */
277 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
279 /* The rest must handle multibyte characters. */
281 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
282 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
283 : 1)
285 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
286 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
287 : 1)
289 # define ISALNUM(c) (IS_REAL_ASCII (c) \
290 ? (((c) >= 'a' && (c) <= 'z') \
291 || ((c) >= 'A' && (c) <= 'Z') \
292 || ((c) >= '0' && (c) <= '9')) \
293 : SYNTAX (c) == Sword)
295 # define ISALPHA(c) (IS_REAL_ASCII (c) \
296 ? (((c) >= 'a' && (c) <= 'z') \
297 || ((c) >= 'A' && (c) <= 'Z')) \
298 : SYNTAX (c) == Sword)
300 # define ISLOWER(c) (LOWERCASEP (c))
302 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
303 ? ((c) > ' ' && (c) < 0177 \
304 && !(((c) >= 'a' && (c) <= 'z') \
305 || ((c) >= 'A' && (c) <= 'Z') \
306 || ((c) >= '0' && (c) <= '9'))) \
307 : SYNTAX (c) != Sword)
309 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
311 # define ISUPPER(c) (UPPERCASEP (c))
313 # define ISWORD(c) (SYNTAX (c) == Sword)
315 #else /* not emacs */
317 /* Jim Meyering writes:
319 "... Some ctype macros are valid only for character codes that
320 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
321 using /bin/cc or gcc but without giving an ansi option). So, all
322 ctype uses should be through macros like ISPRINT... If
323 STDC_HEADERS is defined, then autoconf has verified that the ctype
324 macros don't need to be guarded with references to isascii. ...
325 Defining isascii to 1 should let any compiler worth its salt
326 eliminate the && through constant folding."
327 Solaris defines some of these symbols so we must undefine them first. */
329 # undef ISASCII
330 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
331 # define ISASCII(c) 1
332 # else
333 # define ISASCII(c) isascii(c)
334 # endif
336 /* 1 if C is an ASCII character. */
337 # define IS_REAL_ASCII(c) ((c) < 0200)
339 /* This distinction is not meaningful, except in Emacs. */
340 # define ISUNIBYTE(c) 1
342 # ifdef isblank
343 # define ISBLANK(c) (ISASCII (c) && isblank (c))
344 # else
345 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
346 # endif
347 # ifdef isgraph
348 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
349 # else
350 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
351 # endif
353 # undef ISPRINT
354 # define ISPRINT(c) (ISASCII (c) && isprint (c))
355 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
356 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
357 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
358 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
359 # define ISLOWER(c) (ISASCII (c) && islower (c))
360 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
361 # define ISSPACE(c) (ISASCII (c) && isspace (c))
362 # define ISUPPER(c) (ISASCII (c) && isupper (c))
363 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
365 # define ISWORD(c) ISALPHA(c)
367 # ifdef _tolower
368 # define TOLOWER(c) _tolower(c)
369 # else
370 # define TOLOWER(c) tolower(c)
371 # endif
373 /* How many characters in the character set. */
374 # define CHAR_SET_SIZE 256
376 # ifdef SYNTAX_TABLE
378 extern char *re_syntax_table;
380 # else /* not SYNTAX_TABLE */
382 static char re_syntax_table[CHAR_SET_SIZE];
384 static void
385 init_syntax_once ()
387 register int c;
388 static int done = 0;
390 if (done)
391 return;
393 bzero (re_syntax_table, sizeof re_syntax_table);
395 for (c = 0; c < CHAR_SET_SIZE; ++c)
396 if (ISALNUM (c))
397 re_syntax_table[c] = Sword;
399 re_syntax_table['_'] = Sword;
401 done = 1;
404 # endif /* not SYNTAX_TABLE */
406 # define SYNTAX(c) re_syntax_table[(c)]
408 #endif /* not emacs */
410 #ifndef NULL
411 # define NULL (void *)0
412 #endif
414 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
415 since ours (we hope) works properly with all combinations of
416 machines, compilers, `char' and `unsigned char' argument types.
417 (Per Bothner suggested the basic approach.) */
418 #undef SIGN_EXTEND_CHAR
419 #if __STDC__
420 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
421 #else /* not __STDC__ */
422 /* As in Harbison and Steele. */
423 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
424 #endif
426 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
427 use `alloca' instead of `malloc'. This is because using malloc in
428 re_search* or re_match* could cause memory leaks when C-g is used in
429 Emacs; also, malloc is slower and causes storage fragmentation. On
430 the other hand, malloc is more portable, and easier to debug.
432 Because we sometimes use alloca, some routines have to be macros,
433 not functions -- `alloca'-allocated space disappears at the end of the
434 function it is called in. */
436 #ifdef REGEX_MALLOC
438 # define REGEX_ALLOCATE malloc
439 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
440 # define REGEX_FREE free
442 #else /* not REGEX_MALLOC */
444 /* Emacs already defines alloca, sometimes. */
445 # ifndef alloca
447 /* Make alloca work the best possible way. */
448 # ifdef __GNUC__
449 # define alloca __builtin_alloca
450 # else /* not __GNUC__ */
451 # if HAVE_ALLOCA_H
452 # include <alloca.h>
453 # endif /* HAVE_ALLOCA_H */
454 # endif /* not __GNUC__ */
456 # endif /* not alloca */
458 # define REGEX_ALLOCATE alloca
460 /* Assumes a `char *destination' variable. */
461 # define REGEX_REALLOCATE(source, osize, nsize) \
462 (destination = (char *) alloca (nsize), \
463 memcpy (destination, source, osize))
465 /* No need to do anything to free, after alloca. */
466 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
468 #endif /* not REGEX_MALLOC */
470 /* Define how to allocate the failure stack. */
472 #if defined REL_ALLOC && defined REGEX_MALLOC
474 # define REGEX_ALLOCATE_STACK(size) \
475 r_alloc (&failure_stack_ptr, (size))
476 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
477 r_re_alloc (&failure_stack_ptr, (nsize))
478 # define REGEX_FREE_STACK(ptr) \
479 r_alloc_free (&failure_stack_ptr)
481 #else /* not using relocating allocator */
483 # ifdef REGEX_MALLOC
485 # define REGEX_ALLOCATE_STACK malloc
486 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
487 # define REGEX_FREE_STACK free
489 # else /* not REGEX_MALLOC */
491 # define REGEX_ALLOCATE_STACK alloca
493 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
494 REGEX_REALLOCATE (source, osize, nsize)
495 /* No need to explicitly free anything. */
496 # define REGEX_FREE_STACK(arg) ((void)0)
498 # endif /* not REGEX_MALLOC */
499 #endif /* not using relocating allocator */
502 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
503 `string1' or just past its end. This works if PTR is NULL, which is
504 a good thing. */
505 #define FIRST_STRING_P(ptr) \
506 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
508 /* (Re)Allocate N items of type T using malloc, or fail. */
509 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
510 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
511 #define RETALLOC_IF(addr, n, t) \
512 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
513 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
515 #define BYTEWIDTH 8 /* In bits. */
517 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
519 #undef MAX
520 #undef MIN
521 #define MAX(a, b) ((a) > (b) ? (a) : (b))
522 #define MIN(a, b) ((a) < (b) ? (a) : (b))
524 /* Type of source-pattern and string chars. */
525 typedef const unsigned char re_char;
527 typedef char boolean;
528 #define false 0
529 #define true 1
531 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
532 re_char *string1, int size1,
533 re_char *string2, int size2,
534 int pos,
535 struct re_registers *regs,
536 int stop));
538 /* These are the command codes that appear in compiled regular
539 expressions. Some opcodes are followed by argument bytes. A
540 command code can specify any interpretation whatsoever for its
541 arguments. Zero bytes may appear in the compiled regular expression. */
543 typedef enum
545 no_op = 0,
547 /* Succeed right away--no more backtracking. */
548 succeed,
550 /* Followed by one byte giving n, then by n literal bytes. */
551 exactn,
553 /* Matches any (more or less) character. */
554 anychar,
556 /* Matches any one char belonging to specified set. First
557 following byte is number of bitmap bytes. Then come bytes
558 for a bitmap saying which chars are in. Bits in each byte
559 are ordered low-bit-first. A character is in the set if its
560 bit is 1. A character too large to have a bit in the map is
561 automatically not in the set.
563 If the length byte has the 0x80 bit set, then that stuff
564 is followed by a range table:
565 2 bytes of flags for character sets (low 8 bits, high 8 bits)
566 See RANGE_TABLE_WORK_BITS below.
567 2 bytes, the number of pairs that follow (upto 32767)
568 pairs, each 2 multibyte characters,
569 each multibyte character represented as 3 bytes. */
570 charset,
572 /* Same parameters as charset, but match any character that is
573 not one of those specified. */
574 charset_not,
576 /* Start remembering the text that is matched, for storing in a
577 register. Followed by one byte with the register number, in
578 the range 0 to one less than the pattern buffer's re_nsub
579 field. */
580 start_memory,
582 /* Stop remembering the text that is matched and store it in a
583 memory register. Followed by one byte with the register
584 number, in the range 0 to one less than `re_nsub' in the
585 pattern buffer. */
586 stop_memory,
588 /* Match a duplicate of something remembered. Followed by one
589 byte containing the register number. */
590 duplicate,
592 /* Fail unless at beginning of line. */
593 begline,
595 /* Fail unless at end of line. */
596 endline,
598 /* Succeeds if at beginning of buffer (if emacs) or at beginning
599 of string to be matched (if not). */
600 begbuf,
602 /* Analogously, for end of buffer/string. */
603 endbuf,
605 /* Followed by two byte relative address to which to jump. */
606 jump,
608 /* Followed by two-byte relative address of place to resume at
609 in case of failure. */
610 on_failure_jump,
612 /* Like on_failure_jump, but pushes a placeholder instead of the
613 current string position when executed. */
614 on_failure_keep_string_jump,
616 /* Just like `on_failure_jump', except that it checks that we
617 don't get stuck in an infinite loop (matching an empty string
618 indefinitely). */
619 on_failure_jump_loop,
621 /* Just like `on_failure_jump_loop', except that it checks for
622 a different kind of loop (the kind that shows up with non-greedy
623 operators). This operation has to be immediately preceded
624 by a `no_op'. */
625 on_failure_jump_nastyloop,
627 /* A smart `on_failure_jump' used for greedy * and + operators.
628 It analyses the loop before which it is put and if the
629 loop does not require backtracking, it changes itself to
630 `on_failure_keep_string_jump' and short-circuits the loop,
631 else it just defaults to changing itself into `on_failure_jump'.
632 It assumes that it is pointing to just past a `jump'. */
633 on_failure_jump_smart,
635 /* Followed by two-byte relative address and two-byte number n.
636 After matching N times, jump to the address upon failure.
637 Does not work if N starts at 0: use on_failure_jump_loop
638 instead. */
639 succeed_n,
641 /* Followed by two-byte relative address, and two-byte number n.
642 Jump to the address N times, then fail. */
643 jump_n,
645 /* Set the following two-byte relative address to the
646 subsequent two-byte number. The address *includes* the two
647 bytes of number. */
648 set_number_at,
650 wordbeg, /* Succeeds if at word beginning. */
651 wordend, /* Succeeds if at word end. */
653 wordbound, /* Succeeds if at a word boundary. */
654 notwordbound, /* Succeeds if not at a word boundary. */
656 /* Matches any character whose syntax is specified. Followed by
657 a byte which contains a syntax code, e.g., Sword. */
658 syntaxspec,
660 /* Matches any character whose syntax is not that specified. */
661 notsyntaxspec
663 #ifdef emacs
664 ,before_dot, /* Succeeds if before point. */
665 at_dot, /* Succeeds if at point. */
666 after_dot, /* Succeeds if after point. */
668 /* Matches any character whose category-set contains the specified
669 category. The operator is followed by a byte which contains a
670 category code (mnemonic ASCII character). */
671 categoryspec,
673 /* Matches any character whose category-set does not contain the
674 specified category. The operator is followed by a byte which
675 contains the category code (mnemonic ASCII character). */
676 notcategoryspec
677 #endif /* emacs */
678 } re_opcode_t;
680 /* Common operations on the compiled pattern. */
682 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
684 #define STORE_NUMBER(destination, number) \
685 do { \
686 (destination)[0] = (number) & 0377; \
687 (destination)[1] = (number) >> 8; \
688 } while (0)
690 /* Same as STORE_NUMBER, except increment DESTINATION to
691 the byte after where the number is stored. Therefore, DESTINATION
692 must be an lvalue. */
694 #define STORE_NUMBER_AND_INCR(destination, number) \
695 do { \
696 STORE_NUMBER (destination, number); \
697 (destination) += 2; \
698 } while (0)
700 /* Put into DESTINATION a number stored in two contiguous bytes starting
701 at SOURCE. */
703 #define EXTRACT_NUMBER(destination, source) \
704 do { \
705 (destination) = *(source) & 0377; \
706 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
707 } while (0)
709 #ifdef DEBUG
710 static void extract_number _RE_ARGS ((int *dest, re_char *source));
711 static void
712 extract_number (dest, source)
713 int *dest;
714 re_char *source;
716 int temp = SIGN_EXTEND_CHAR (*(source + 1));
717 *dest = *source & 0377;
718 *dest += temp << 8;
721 # ifndef EXTRACT_MACROS /* To debug the macros. */
722 # undef EXTRACT_NUMBER
723 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
724 # endif /* not EXTRACT_MACROS */
726 #endif /* DEBUG */
728 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
729 SOURCE must be an lvalue. */
731 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
732 do { \
733 EXTRACT_NUMBER (destination, source); \
734 (source) += 2; \
735 } while (0)
737 #ifdef DEBUG
738 static void extract_number_and_incr _RE_ARGS ((int *destination,
739 re_char **source));
740 static void
741 extract_number_and_incr (destination, source)
742 int *destination;
743 re_char **source;
745 extract_number (destination, *source);
746 *source += 2;
749 # ifndef EXTRACT_MACROS
750 # undef EXTRACT_NUMBER_AND_INCR
751 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
752 extract_number_and_incr (&dest, &src)
753 # endif /* not EXTRACT_MACROS */
755 #endif /* DEBUG */
757 /* Store a multibyte character in three contiguous bytes starting
758 DESTINATION, and increment DESTINATION to the byte after where the
759 character is stored. Therefore, DESTINATION must be an lvalue. */
761 #define STORE_CHARACTER_AND_INCR(destination, character) \
762 do { \
763 (destination)[0] = (character) & 0377; \
764 (destination)[1] = ((character) >> 8) & 0377; \
765 (destination)[2] = (character) >> 16; \
766 (destination) += 3; \
767 } while (0)
769 /* Put into DESTINATION a character stored in three contiguous bytes
770 starting at SOURCE. */
772 #define EXTRACT_CHARACTER(destination, source) \
773 do { \
774 (destination) = ((source)[0] \
775 | ((source)[1] << 8) \
776 | ((source)[2] << 16)); \
777 } while (0)
780 /* Macros for charset. */
782 /* Size of bitmap of charset P in bytes. P is a start of charset,
783 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
784 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
786 /* Nonzero if charset P has range table. */
787 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
789 /* Return the address of range table of charset P. But not the start
790 of table itself, but the before where the number of ranges is
791 stored. `2 +' means to skip re_opcode_t and size of bitmap,
792 and the 2 bytes of flags at the start of the range table. */
793 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
795 /* Extract the bit flags that start a range table. */
796 #define CHARSET_RANGE_TABLE_BITS(p) \
797 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
798 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
800 /* Test if C is listed in the bitmap of charset P. */
801 #define CHARSET_LOOKUP_BITMAP(p, c) \
802 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
803 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
805 /* Return the address of end of RANGE_TABLE. COUNT is number of
806 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
807 is start of range and end of range. `* 3' is size of each start
808 and end. */
809 #define CHARSET_RANGE_TABLE_END(range_table, count) \
810 ((range_table) + (count) * 2 * 3)
812 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
813 COUNT is number of ranges in RANGE_TABLE. */
814 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
815 do \
817 re_wchar_t range_start, range_end; \
818 re_char *p; \
819 re_char *range_table_end \
820 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
822 for (p = (range_table); p < range_table_end; p += 2 * 3) \
824 EXTRACT_CHARACTER (range_start, p); \
825 EXTRACT_CHARACTER (range_end, p + 3); \
827 if (range_start <= (c) && (c) <= range_end) \
829 (not) = !(not); \
830 break; \
834 while (0)
836 /* Test if C is in range table of CHARSET. The flag NOT is negated if
837 C is listed in it. */
838 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
839 do \
841 /* Number of ranges in range table. */ \
842 int count; \
843 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
845 EXTRACT_NUMBER_AND_INCR (count, range_table); \
846 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
848 while (0)
850 /* If DEBUG is defined, Regex prints many voluminous messages about what
851 it is doing (if the variable `debug' is nonzero). If linked with the
852 main program in `iregex.c', you can enter patterns and strings
853 interactively. And if linked with the main program in `main.c' and
854 the other test files, you can run the already-written tests. */
856 #ifdef DEBUG
858 /* We use standard I/O for debugging. */
859 # include <stdio.h>
861 /* It is useful to test things that ``must'' be true when debugging. */
862 # include <assert.h>
864 static int debug = -100000;
866 # define DEBUG_STATEMENT(e) e
867 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
868 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
869 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
870 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
871 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
872 if (debug > 0) print_partial_compiled_pattern (s, e)
873 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
874 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
877 /* Print the fastmap in human-readable form. */
879 void
880 print_fastmap (fastmap)
881 char *fastmap;
883 unsigned was_a_range = 0;
884 unsigned i = 0;
886 while (i < (1 << BYTEWIDTH))
888 if (fastmap[i++])
890 was_a_range = 0;
891 putchar (i - 1);
892 while (i < (1 << BYTEWIDTH) && fastmap[i])
894 was_a_range = 1;
895 i++;
897 if (was_a_range)
899 printf ("-");
900 putchar (i - 1);
904 putchar ('\n');
908 /* Print a compiled pattern string in human-readable form, starting at
909 the START pointer into it and ending just before the pointer END. */
911 void
912 print_partial_compiled_pattern (start, end)
913 re_char *start;
914 re_char *end;
916 int mcnt, mcnt2;
917 re_char *p = start;
918 re_char *pend = end;
920 if (start == NULL)
922 printf ("(null)\n");
923 return;
926 /* Loop over pattern commands. */
927 while (p < pend)
929 printf ("%d:\t", p - start);
931 switch ((re_opcode_t) *p++)
933 case no_op:
934 printf ("/no_op");
935 break;
937 case succeed:
938 printf ("/succeed");
939 break;
941 case exactn:
942 mcnt = *p++;
943 printf ("/exactn/%d", mcnt);
946 putchar ('/');
947 putchar (*p++);
949 while (--mcnt);
950 break;
952 case start_memory:
953 printf ("/start_memory/%d", *p++);
954 break;
956 case stop_memory:
957 printf ("/stop_memory/%d", *p++);
958 break;
960 case duplicate:
961 printf ("/duplicate/%d", *p++);
962 break;
964 case anychar:
965 printf ("/anychar");
966 break;
968 case charset:
969 case charset_not:
971 register int c, last = -100;
972 register int in_range = 0;
973 int length = CHARSET_BITMAP_SIZE (p - 1);
974 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
976 printf ("/charset [%s",
977 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
979 assert (p + *p < pend);
981 for (c = 0; c < 256; c++)
982 if (c / 8 < length
983 && (p[1 + (c/8)] & (1 << (c % 8))))
985 /* Are we starting a range? */
986 if (last + 1 == c && ! in_range)
988 putchar ('-');
989 in_range = 1;
991 /* Have we broken a range? */
992 else if (last + 1 != c && in_range)
994 putchar (last);
995 in_range = 0;
998 if (! in_range)
999 putchar (c);
1001 last = c;
1004 if (in_range)
1005 putchar (last);
1007 putchar (']');
1009 p += 1 + length;
1011 if (has_range_table)
1013 int count;
1014 printf ("has-range-table");
1016 /* ??? Should print the range table; for now, just skip it. */
1017 p += 2; /* skip range table bits */
1018 EXTRACT_NUMBER_AND_INCR (count, p);
1019 p = CHARSET_RANGE_TABLE_END (p, count);
1022 break;
1024 case begline:
1025 printf ("/begline");
1026 break;
1028 case endline:
1029 printf ("/endline");
1030 break;
1032 case on_failure_jump:
1033 extract_number_and_incr (&mcnt, &p);
1034 printf ("/on_failure_jump to %d", p + mcnt - start);
1035 break;
1037 case on_failure_keep_string_jump:
1038 extract_number_and_incr (&mcnt, &p);
1039 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
1040 break;
1042 case on_failure_jump_nastyloop:
1043 extract_number_and_incr (&mcnt, &p);
1044 printf ("/on_failure_jump_nastyloop to %d", p + mcnt - start);
1045 break;
1047 case on_failure_jump_loop:
1048 extract_number_and_incr (&mcnt, &p);
1049 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
1050 break;
1052 case on_failure_jump_smart:
1053 extract_number_and_incr (&mcnt, &p);
1054 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
1055 break;
1057 case jump:
1058 extract_number_and_incr (&mcnt, &p);
1059 printf ("/jump to %d", p + mcnt - start);
1060 break;
1062 case succeed_n:
1063 extract_number_and_incr (&mcnt, &p);
1064 extract_number_and_incr (&mcnt2, &p);
1065 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1066 break;
1068 case jump_n:
1069 extract_number_and_incr (&mcnt, &p);
1070 extract_number_and_incr (&mcnt2, &p);
1071 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1072 break;
1074 case set_number_at:
1075 extract_number_and_incr (&mcnt, &p);
1076 extract_number_and_incr (&mcnt2, &p);
1077 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1078 break;
1080 case wordbound:
1081 printf ("/wordbound");
1082 break;
1084 case notwordbound:
1085 printf ("/notwordbound");
1086 break;
1088 case wordbeg:
1089 printf ("/wordbeg");
1090 break;
1092 case wordend:
1093 printf ("/wordend");
1095 case syntaxspec:
1096 printf ("/syntaxspec");
1097 mcnt = *p++;
1098 printf ("/%d", mcnt);
1099 break;
1101 case notsyntaxspec:
1102 printf ("/notsyntaxspec");
1103 mcnt = *p++;
1104 printf ("/%d", mcnt);
1105 break;
1107 # ifdef emacs
1108 case before_dot:
1109 printf ("/before_dot");
1110 break;
1112 case at_dot:
1113 printf ("/at_dot");
1114 break;
1116 case after_dot:
1117 printf ("/after_dot");
1118 break;
1120 case categoryspec:
1121 printf ("/categoryspec");
1122 mcnt = *p++;
1123 printf ("/%d", mcnt);
1124 break;
1126 case notcategoryspec:
1127 printf ("/notcategoryspec");
1128 mcnt = *p++;
1129 printf ("/%d", mcnt);
1130 break;
1131 # endif /* emacs */
1133 case begbuf:
1134 printf ("/begbuf");
1135 break;
1137 case endbuf:
1138 printf ("/endbuf");
1139 break;
1141 default:
1142 printf ("?%d", *(p-1));
1145 putchar ('\n');
1148 printf ("%d:\tend of pattern.\n", p - start);
1152 void
1153 print_compiled_pattern (bufp)
1154 struct re_pattern_buffer *bufp;
1156 re_char *buffer = bufp->buffer;
1158 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1159 printf ("%ld bytes used/%ld bytes allocated.\n",
1160 bufp->used, bufp->allocated);
1162 if (bufp->fastmap_accurate && bufp->fastmap)
1164 printf ("fastmap: ");
1165 print_fastmap (bufp->fastmap);
1168 printf ("re_nsub: %d\t", bufp->re_nsub);
1169 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1170 printf ("can_be_null: %d\t", bufp->can_be_null);
1171 printf ("no_sub: %d\t", bufp->no_sub);
1172 printf ("not_bol: %d\t", bufp->not_bol);
1173 printf ("not_eol: %d\t", bufp->not_eol);
1174 printf ("syntax: %lx\n", bufp->syntax);
1175 fflush (stdout);
1176 /* Perhaps we should print the translate table? */
1180 void
1181 print_double_string (where, string1, size1, string2, size2)
1182 re_char *where;
1183 re_char *string1;
1184 re_char *string2;
1185 int size1;
1186 int size2;
1188 int this_char;
1190 if (where == NULL)
1191 printf ("(null)");
1192 else
1194 if (FIRST_STRING_P (where))
1196 for (this_char = where - string1; this_char < size1; this_char++)
1197 putchar (string1[this_char]);
1199 where = string2;
1202 for (this_char = where - string2; this_char < size2; this_char++)
1203 putchar (string2[this_char]);
1207 #else /* not DEBUG */
1209 # undef assert
1210 # define assert(e)
1212 # define DEBUG_STATEMENT(e)
1213 # define DEBUG_PRINT1(x)
1214 # define DEBUG_PRINT2(x1, x2)
1215 # define DEBUG_PRINT3(x1, x2, x3)
1216 # define DEBUG_PRINT4(x1, x2, x3, x4)
1217 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1218 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1220 #endif /* not DEBUG */
1222 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1223 also be assigned to arbitrarily: each pattern buffer stores its own
1224 syntax, so it can be changed between regex compilations. */
1225 /* This has no initializer because initialized variables in Emacs
1226 become read-only after dumping. */
1227 reg_syntax_t re_syntax_options;
1230 /* Specify the precise syntax of regexps for compilation. This provides
1231 for compatibility for various utilities which historically have
1232 different, incompatible syntaxes.
1234 The argument SYNTAX is a bit mask comprised of the various bits
1235 defined in regex.h. We return the old syntax. */
1237 reg_syntax_t
1238 re_set_syntax (syntax)
1239 reg_syntax_t syntax;
1241 reg_syntax_t ret = re_syntax_options;
1243 re_syntax_options = syntax;
1244 return ret;
1246 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1248 /* This table gives an error message for each of the error codes listed
1249 in regex.h. Obviously the order here has to be same as there.
1250 POSIX doesn't require that we do anything for REG_NOERROR,
1251 but why not be nice? */
1253 static const char *re_error_msgid[] =
1255 gettext_noop ("Success"), /* REG_NOERROR */
1256 gettext_noop ("No match"), /* REG_NOMATCH */
1257 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1258 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1259 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1260 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1261 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1262 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1263 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1264 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1265 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1266 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1267 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1268 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1269 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1270 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1271 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1274 /* Avoiding alloca during matching, to placate r_alloc. */
1276 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1277 searching and matching functions should not call alloca. On some
1278 systems, alloca is implemented in terms of malloc, and if we're
1279 using the relocating allocator routines, then malloc could cause a
1280 relocation, which might (if the strings being searched are in the
1281 ralloc heap) shift the data out from underneath the regexp
1282 routines.
1284 Here's another reason to avoid allocation: Emacs
1285 processes input from X in a signal handler; processing X input may
1286 call malloc; if input arrives while a matching routine is calling
1287 malloc, then we're scrod. But Emacs can't just block input while
1288 calling matching routines; then we don't notice interrupts when
1289 they come in. So, Emacs blocks input around all regexp calls
1290 except the matching calls, which it leaves unprotected, in the
1291 faith that they will not malloc. */
1293 /* Normally, this is fine. */
1294 #define MATCH_MAY_ALLOCATE
1296 /* When using GNU C, we are not REALLY using the C alloca, no matter
1297 what config.h may say. So don't take precautions for it. */
1298 #ifdef __GNUC__
1299 # undef C_ALLOCA
1300 #endif
1302 /* The match routines may not allocate if (1) they would do it with malloc
1303 and (2) it's not safe for them to use malloc.
1304 Note that if REL_ALLOC is defined, matching would not use malloc for the
1305 failure stack, but we would still use it for the register vectors;
1306 so REL_ALLOC should not affect this. */
1307 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1308 # undef MATCH_MAY_ALLOCATE
1309 #endif
1312 /* Failure stack declarations and macros; both re_compile_fastmap and
1313 re_match_2 use a failure stack. These have to be macros because of
1314 REGEX_ALLOCATE_STACK. */
1317 /* Approximate number of failure points for which to initially allocate space
1318 when matching. If this number is exceeded, we allocate more
1319 space, so it is not a hard limit. */
1320 #ifndef INIT_FAILURE_ALLOC
1321 # define INIT_FAILURE_ALLOC 20
1322 #endif
1324 /* Roughly the maximum number of failure points on the stack. Would be
1325 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1326 This is a variable only so users of regex can assign to it; we never
1327 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1328 before using it, so it should probably be a byte-count instead. */
1329 # if defined MATCH_MAY_ALLOCATE
1330 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1331 whose default stack limit is 2mb. In order for a larger
1332 value to work reliably, you have to try to make it accord
1333 with the process stack limit. */
1334 size_t re_max_failures = 40000;
1335 # else
1336 size_t re_max_failures = 4000;
1337 # endif
1339 union fail_stack_elt
1341 re_char *pointer;
1342 /* This should be the biggest `int' that's no bigger than a pointer. */
1343 long integer;
1346 typedef union fail_stack_elt fail_stack_elt_t;
1348 typedef struct
1350 fail_stack_elt_t *stack;
1351 size_t size;
1352 size_t avail; /* Offset of next open position. */
1353 size_t frame; /* Offset of the cur constructed frame. */
1354 } fail_stack_type;
1356 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1357 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1360 /* Define macros to initialize and free the failure stack.
1361 Do `return -2' if the alloc fails. */
1363 #ifdef MATCH_MAY_ALLOCATE
1364 # define INIT_FAIL_STACK() \
1365 do { \
1366 fail_stack.stack = (fail_stack_elt_t *) \
1367 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1368 * sizeof (fail_stack_elt_t)); \
1370 if (fail_stack.stack == NULL) \
1371 return -2; \
1373 fail_stack.size = INIT_FAILURE_ALLOC; \
1374 fail_stack.avail = 0; \
1375 fail_stack.frame = 0; \
1376 } while (0)
1378 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1379 #else
1380 # define INIT_FAIL_STACK() \
1381 do { \
1382 fail_stack.avail = 0; \
1383 fail_stack.frame = 0; \
1384 } while (0)
1386 # define RESET_FAIL_STACK() ((void)0)
1387 #endif
1390 /* Double the size of FAIL_STACK, up to a limit
1391 which allows approximately `re_max_failures' items.
1393 Return 1 if succeeds, and 0 if either ran out of memory
1394 allocating space for it or it was already too large.
1396 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1398 /* Factor to increase the failure stack size by
1399 when we increase it.
1400 This used to be 2, but 2 was too wasteful
1401 because the old discarded stacks added up to as much space
1402 were as ultimate, maximum-size stack. */
1403 #define FAIL_STACK_GROWTH_FACTOR 4
1405 #define GROW_FAIL_STACK(fail_stack) \
1406 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1407 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1408 ? 0 \
1409 : ((fail_stack).stack \
1410 = (fail_stack_elt_t *) \
1411 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1412 (fail_stack).size * sizeof (fail_stack_elt_t), \
1413 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1414 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1415 * FAIL_STACK_GROWTH_FACTOR))), \
1417 (fail_stack).stack == NULL \
1418 ? 0 \
1419 : ((fail_stack).size \
1420 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1421 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1422 * FAIL_STACK_GROWTH_FACTOR)) \
1423 / sizeof (fail_stack_elt_t)), \
1424 1)))
1427 /* Push a pointer value onto the failure stack.
1428 Assumes the variable `fail_stack'. Probably should only
1429 be called from within `PUSH_FAILURE_POINT'. */
1430 #define PUSH_FAILURE_POINTER(item) \
1431 fail_stack.stack[fail_stack.avail++].pointer = (item)
1433 /* This pushes an integer-valued item onto the failure stack.
1434 Assumes the variable `fail_stack'. Probably should only
1435 be called from within `PUSH_FAILURE_POINT'. */
1436 #define PUSH_FAILURE_INT(item) \
1437 fail_stack.stack[fail_stack.avail++].integer = (item)
1439 /* Push a fail_stack_elt_t value onto the failure stack.
1440 Assumes the variable `fail_stack'. Probably should only
1441 be called from within `PUSH_FAILURE_POINT'. */
1442 #define PUSH_FAILURE_ELT(item) \
1443 fail_stack.stack[fail_stack.avail++] = (item)
1445 /* These three POP... operations complement the three PUSH... operations.
1446 All assume that `fail_stack' is nonempty. */
1447 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1448 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1449 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1451 /* Individual items aside from the registers. */
1452 #define NUM_NONREG_ITEMS 3
1454 /* Used to examine the stack (to detect infinite loops). */
1455 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1456 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1457 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1458 #define TOP_FAILURE_HANDLE() fail_stack.frame
1461 #define ENSURE_FAIL_STACK(space) \
1462 while (REMAINING_AVAIL_SLOTS <= space) { \
1463 if (!GROW_FAIL_STACK (fail_stack)) \
1464 return -2; \
1465 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1466 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1469 /* Push register NUM onto the stack. */
1470 #define PUSH_FAILURE_REG(num) \
1471 do { \
1472 char *destination; \
1473 ENSURE_FAIL_STACK(3); \
1474 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1475 num, regstart[num], regend[num]); \
1476 PUSH_FAILURE_POINTER (regstart[num]); \
1477 PUSH_FAILURE_POINTER (regend[num]); \
1478 PUSH_FAILURE_INT (num); \
1479 } while (0)
1481 /* Change the counter's value to VAL, but make sure that it will
1482 be reset when backtracking. */
1483 #define PUSH_NUMBER(ptr,val) \
1484 do { \
1485 char *destination; \
1486 int c; \
1487 ENSURE_FAIL_STACK(3); \
1488 EXTRACT_NUMBER (c, ptr); \
1489 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1490 PUSH_FAILURE_INT (c); \
1491 PUSH_FAILURE_POINTER (ptr); \
1492 PUSH_FAILURE_INT (-1); \
1493 STORE_NUMBER (ptr, val); \
1494 } while (0)
1496 /* Pop a saved register off the stack. */
1497 #define POP_FAILURE_REG_OR_COUNT() \
1498 do { \
1499 int reg = POP_FAILURE_INT (); \
1500 if (reg == -1) \
1502 /* It's a counter. */ \
1503 /* Here, we discard `const', making re_match non-reentrant. */ \
1504 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1505 reg = POP_FAILURE_INT (); \
1506 STORE_NUMBER (ptr, reg); \
1507 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1509 else \
1511 regend[reg] = POP_FAILURE_POINTER (); \
1512 regstart[reg] = POP_FAILURE_POINTER (); \
1513 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1514 reg, regstart[reg], regend[reg]); \
1516 } while (0)
1518 /* Check that we are not stuck in an infinite loop. */
1519 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1520 do { \
1521 int failure = TOP_FAILURE_HANDLE (); \
1522 /* Check for infinite matching loops */ \
1523 while (failure > 0 \
1524 && (FAILURE_STR (failure) == string_place \
1525 || FAILURE_STR (failure) == NULL)) \
1527 assert (FAILURE_PAT (failure) >= bufp->buffer \
1528 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1529 if (FAILURE_PAT (failure) == pat_cur) \
1531 cycle = 1; \
1532 break; \
1534 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1535 failure = NEXT_FAILURE_HANDLE(failure); \
1537 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1538 } while (0)
1540 /* Push the information about the state we will need
1541 if we ever fail back to it.
1543 Requires variables fail_stack, regstart, regend and
1544 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1545 declared.
1547 Does `return FAILURE_CODE' if runs out of memory. */
1549 #define PUSH_FAILURE_POINT(pattern, string_place) \
1550 do { \
1551 char *destination; \
1552 /* Must be int, so when we don't save any registers, the arithmetic \
1553 of 0 + -1 isn't done as unsigned. */ \
1555 DEBUG_STATEMENT (nfailure_points_pushed++); \
1556 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1557 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1558 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1560 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1562 DEBUG_PRINT1 ("\n"); \
1564 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1565 PUSH_FAILURE_INT (fail_stack.frame); \
1567 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1568 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1569 DEBUG_PRINT1 ("'\n"); \
1570 PUSH_FAILURE_POINTER (string_place); \
1572 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1573 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1574 PUSH_FAILURE_POINTER (pattern); \
1576 /* Close the frame by moving the frame pointer past it. */ \
1577 fail_stack.frame = fail_stack.avail; \
1578 } while (0)
1580 /* Estimate the size of data pushed by a typical failure stack entry.
1581 An estimate is all we need, because all we use this for
1582 is to choose a limit for how big to make the failure stack. */
1583 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1584 #define TYPICAL_FAILURE_SIZE 20
1586 /* How many items can still be added to the stack without overflowing it. */
1587 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1590 /* Pops what PUSH_FAIL_STACK pushes.
1592 We restore into the parameters, all of which should be lvalues:
1593 STR -- the saved data position.
1594 PAT -- the saved pattern position.
1595 REGSTART, REGEND -- arrays of string positions.
1597 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1598 `pend', `string1', `size1', `string2', and `size2'. */
1600 #define POP_FAILURE_POINT(str, pat) \
1601 do { \
1602 assert (!FAIL_STACK_EMPTY ()); \
1604 /* Remove failure points and point to how many regs pushed. */ \
1605 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1606 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1607 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1609 /* Pop the saved registers. */ \
1610 while (fail_stack.frame < fail_stack.avail) \
1611 POP_FAILURE_REG_OR_COUNT (); \
1613 pat = POP_FAILURE_POINTER (); \
1614 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1615 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1617 /* If the saved string location is NULL, it came from an \
1618 on_failure_keep_string_jump opcode, and we want to throw away the \
1619 saved NULL, thus retaining our current position in the string. */ \
1620 str = POP_FAILURE_POINTER (); \
1621 DEBUG_PRINT2 (" Popping string %p: `", str); \
1622 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1623 DEBUG_PRINT1 ("'\n"); \
1625 fail_stack.frame = POP_FAILURE_INT (); \
1626 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1628 assert (fail_stack.avail >= 0); \
1629 assert (fail_stack.frame <= fail_stack.avail); \
1631 DEBUG_STATEMENT (nfailure_points_popped++); \
1632 } while (0) /* POP_FAILURE_POINT */
1636 /* Registers are set to a sentinel when they haven't yet matched. */
1637 #define REG_UNSET(e) ((e) == NULL)
1639 /* Subroutine declarations and macros for regex_compile. */
1641 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1642 reg_syntax_t syntax,
1643 struct re_pattern_buffer *bufp));
1644 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1645 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1646 int arg1, int arg2));
1647 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1648 int arg, unsigned char *end));
1649 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1650 int arg1, int arg2, unsigned char *end));
1651 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1652 re_char *p,
1653 reg_syntax_t syntax));
1654 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1655 re_char *pend,
1656 reg_syntax_t syntax));
1657 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1658 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1659 char *fastmap, const int multibyte));
1661 /* Fetch the next character in the uncompiled pattern, with no
1662 translation. */
1663 #define PATFETCH(c) \
1664 do { \
1665 int len; \
1666 if (p == pend) return REG_EEND; \
1667 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1668 p += len; \
1669 } while (0)
1672 /* If `translate' is non-null, return translate[D], else just D. We
1673 cast the subscript to translate because some data is declared as
1674 `char *', to avoid warnings when a string constant is passed. But
1675 when we use a character as a subscript we must make it unsigned. */
1676 #ifndef TRANSLATE
1677 # define TRANSLATE(d) \
1678 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1679 #endif
1682 /* Macros for outputting the compiled pattern into `buffer'. */
1684 /* If the buffer isn't allocated when it comes in, use this. */
1685 #define INIT_BUF_SIZE 32
1687 /* Make sure we have at least N more bytes of space in buffer. */
1688 #define GET_BUFFER_SPACE(n) \
1689 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1690 EXTEND_BUFFER ()
1692 /* Make sure we have one more byte of buffer space and then add C to it. */
1693 #define BUF_PUSH(c) \
1694 do { \
1695 GET_BUFFER_SPACE (1); \
1696 *b++ = (unsigned char) (c); \
1697 } while (0)
1700 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1701 #define BUF_PUSH_2(c1, c2) \
1702 do { \
1703 GET_BUFFER_SPACE (2); \
1704 *b++ = (unsigned char) (c1); \
1705 *b++ = (unsigned char) (c2); \
1706 } while (0)
1709 /* As with BUF_PUSH_2, except for three bytes. */
1710 #define BUF_PUSH_3(c1, c2, c3) \
1711 do { \
1712 GET_BUFFER_SPACE (3); \
1713 *b++ = (unsigned char) (c1); \
1714 *b++ = (unsigned char) (c2); \
1715 *b++ = (unsigned char) (c3); \
1716 } while (0)
1719 /* Store a jump with opcode OP at LOC to location TO. We store a
1720 relative address offset by the three bytes the jump itself occupies. */
1721 #define STORE_JUMP(op, loc, to) \
1722 store_op1 (op, loc, (to) - (loc) - 3)
1724 /* Likewise, for a two-argument jump. */
1725 #define STORE_JUMP2(op, loc, to, arg) \
1726 store_op2 (op, loc, (to) - (loc) - 3, arg)
1728 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1729 #define INSERT_JUMP(op, loc, to) \
1730 insert_op1 (op, loc, (to) - (loc) - 3, b)
1732 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1733 #define INSERT_JUMP2(op, loc, to, arg) \
1734 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1737 /* This is not an arbitrary limit: the arguments which represent offsets
1738 into the pattern are two bytes long. So if 2^16 bytes turns out to
1739 be too small, many things would have to change. */
1740 /* Any other compiler which, like MSC, has allocation limit below 2^16
1741 bytes will have to use approach similar to what was done below for
1742 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1743 reallocating to 0 bytes. Such thing is not going to work too well.
1744 You have been warned!! */
1745 #if defined _MSC_VER && !defined WIN32
1746 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1747 # define MAX_BUF_SIZE 65500L
1748 #else
1749 # define MAX_BUF_SIZE (1L << 16)
1750 #endif
1752 /* Extend the buffer by twice its current size via realloc and
1753 reset the pointers that pointed into the old block to point to the
1754 correct places in the new one. If extending the buffer results in it
1755 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1756 #if __BOUNDED_POINTERS__
1757 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1758 # define MOVE_BUFFER_POINTER(P) \
1759 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1760 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1761 else \
1763 SET_HIGH_BOUND (b); \
1764 SET_HIGH_BOUND (begalt); \
1765 if (fixup_alt_jump) \
1766 SET_HIGH_BOUND (fixup_alt_jump); \
1767 if (laststart) \
1768 SET_HIGH_BOUND (laststart); \
1769 if (pending_exact) \
1770 SET_HIGH_BOUND (pending_exact); \
1772 #else
1773 # define MOVE_BUFFER_POINTER(P) (P) += incr
1774 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1775 #endif
1776 #define EXTEND_BUFFER() \
1777 do { \
1778 re_char *old_buffer = bufp->buffer; \
1779 if (bufp->allocated == MAX_BUF_SIZE) \
1780 return REG_ESIZE; \
1781 bufp->allocated <<= 1; \
1782 if (bufp->allocated > MAX_BUF_SIZE) \
1783 bufp->allocated = MAX_BUF_SIZE; \
1784 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1785 if (bufp->buffer == NULL) \
1786 return REG_ESPACE; \
1787 /* If the buffer moved, move all the pointers into it. */ \
1788 if (old_buffer != bufp->buffer) \
1790 int incr = bufp->buffer - old_buffer; \
1791 MOVE_BUFFER_POINTER (b); \
1792 MOVE_BUFFER_POINTER (begalt); \
1793 if (fixup_alt_jump) \
1794 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1795 if (laststart) \
1796 MOVE_BUFFER_POINTER (laststart); \
1797 if (pending_exact) \
1798 MOVE_BUFFER_POINTER (pending_exact); \
1800 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1801 } while (0)
1804 /* Since we have one byte reserved for the register number argument to
1805 {start,stop}_memory, the maximum number of groups we can report
1806 things about is what fits in that byte. */
1807 #define MAX_REGNUM 255
1809 /* But patterns can have more than `MAX_REGNUM' registers. We just
1810 ignore the excess. */
1811 typedef int regnum_t;
1814 /* Macros for the compile stack. */
1816 /* Since offsets can go either forwards or backwards, this type needs to
1817 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1818 /* int may be not enough when sizeof(int) == 2. */
1819 typedef long pattern_offset_t;
1821 typedef struct
1823 pattern_offset_t begalt_offset;
1824 pattern_offset_t fixup_alt_jump;
1825 pattern_offset_t laststart_offset;
1826 regnum_t regnum;
1827 } compile_stack_elt_t;
1830 typedef struct
1832 compile_stack_elt_t *stack;
1833 unsigned size;
1834 unsigned avail; /* Offset of next open position. */
1835 } compile_stack_type;
1838 #define INIT_COMPILE_STACK_SIZE 32
1840 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1841 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1843 /* The next available element. */
1844 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1846 /* Explicit quit checking is only used on NTemacs. */
1847 #if defined WINDOWSNT && defined emacs && defined QUIT
1848 extern int immediate_quit;
1849 # define IMMEDIATE_QUIT_CHECK \
1850 do { \
1851 if (immediate_quit) QUIT; \
1852 } while (0)
1853 #else
1854 # define IMMEDIATE_QUIT_CHECK ((void)0)
1855 #endif
1857 /* Structure to manage work area for range table. */
1858 struct range_table_work_area
1860 int *table; /* actual work area. */
1861 int allocated; /* allocated size for work area in bytes. */
1862 int used; /* actually used size in words. */
1863 int bits; /* flag to record character classes */
1866 /* Make sure that WORK_AREA can hold more N multibyte characters.
1867 This is used only in set_image_of_range and set_image_of_range_1.
1868 It expects WORK_AREA to be a pointer.
1869 If it can't get the space, it returns from the surrounding function. */
1871 #define EXTEND_RANGE_TABLE(work_area, n) \
1872 do { \
1873 if (((work_area)->used + (n)) * sizeof (int) > (work_area)->allocated) \
1875 extend_range_table_work_area (work_area); \
1876 if ((work_area)->table == 0) \
1877 return (REG_ESPACE); \
1879 } while (0)
1881 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1882 (work_area).bits |= (bit)
1884 /* Bits used to implement the multibyte-part of the various character classes
1885 such as [:alnum:] in a charset's range table. */
1886 #define BIT_WORD 0x1
1887 #define BIT_LOWER 0x2
1888 #define BIT_PUNCT 0x4
1889 #define BIT_SPACE 0x8
1890 #define BIT_UPPER 0x10
1891 #define BIT_MULTIBYTE 0x20
1893 /* Set a range START..END to WORK_AREA.
1894 The range is passed through TRANSLATE, so START and END
1895 should be untranslated. */
1896 #define SET_RANGE_TABLE_WORK_AREA(work_area, start, end) \
1897 do { \
1898 int tem; \
1899 tem = set_image_of_range (&work_area, start, end, translate); \
1900 if (tem > 0) \
1901 FREE_STACK_RETURN (tem); \
1902 } while (0)
1904 /* Free allocated memory for WORK_AREA. */
1905 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1906 do { \
1907 if ((work_area).table) \
1908 free ((work_area).table); \
1909 } while (0)
1911 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1912 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1913 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1914 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1917 /* Set the bit for character C in a list. */
1918 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1921 /* Get the next unsigned number in the uncompiled pattern. */
1922 #define GET_UNSIGNED_NUMBER(num) \
1923 do { if (p != pend) \
1925 PATFETCH (c); \
1926 if (c == ' ') \
1927 FREE_STACK_RETURN (REG_BADBR); \
1928 while ('0' <= c && c <= '9') \
1930 int prev; \
1931 if (num < 0) \
1932 num = 0; \
1933 prev = num; \
1934 num = num * 10 + c - '0'; \
1935 if (num / 10 != prev) \
1936 FREE_STACK_RETURN (REG_BADBR); \
1937 if (p == pend) \
1938 break; \
1939 PATFETCH (c); \
1941 if (c == ' ') \
1942 FREE_STACK_RETURN (REG_BADBR); \
1944 } while (0)
1946 #if WIDE_CHAR_SUPPORT
1947 /* The GNU C library provides support for user-defined character classes
1948 and the functions from ISO C amendement 1. */
1949 # ifdef CHARCLASS_NAME_MAX
1950 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1951 # else
1952 /* This shouldn't happen but some implementation might still have this
1953 problem. Use a reasonable default value. */
1954 # define CHAR_CLASS_MAX_LENGTH 256
1955 # endif
1956 typedef wctype_t re_wctype_t;
1957 typedef wchar_t re_wchar_t;
1958 # define re_wctype wctype
1959 # define re_iswctype iswctype
1960 # define re_wctype_to_bit(cc) 0
1961 #else
1962 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1963 # define btowc(c) c
1965 /* Character classes. */
1966 typedef enum { RECC_ERROR = 0,
1967 RECC_ALNUM, RECC_ALPHA, RECC_WORD,
1968 RECC_GRAPH, RECC_PRINT,
1969 RECC_LOWER, RECC_UPPER,
1970 RECC_PUNCT, RECC_CNTRL,
1971 RECC_DIGIT, RECC_XDIGIT,
1972 RECC_BLANK, RECC_SPACE,
1973 RECC_MULTIBYTE, RECC_NONASCII,
1974 RECC_ASCII, RECC_UNIBYTE
1975 } re_wctype_t;
1977 typedef int re_wchar_t;
1979 /* Map a string to the char class it names (if any). */
1980 static re_wctype_t
1981 re_wctype (str)
1982 re_char *str;
1984 const char *string = str;
1985 if (STREQ (string, "alnum")) return RECC_ALNUM;
1986 else if (STREQ (string, "alpha")) return RECC_ALPHA;
1987 else if (STREQ (string, "word")) return RECC_WORD;
1988 else if (STREQ (string, "ascii")) return RECC_ASCII;
1989 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
1990 else if (STREQ (string, "graph")) return RECC_GRAPH;
1991 else if (STREQ (string, "lower")) return RECC_LOWER;
1992 else if (STREQ (string, "print")) return RECC_PRINT;
1993 else if (STREQ (string, "punct")) return RECC_PUNCT;
1994 else if (STREQ (string, "space")) return RECC_SPACE;
1995 else if (STREQ (string, "upper")) return RECC_UPPER;
1996 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
1997 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
1998 else if (STREQ (string, "digit")) return RECC_DIGIT;
1999 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2000 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2001 else if (STREQ (string, "blank")) return RECC_BLANK;
2002 else return 0;
2005 /* True iff CH is in the char class CC. */
2006 static boolean
2007 re_iswctype (ch, cc)
2008 int ch;
2009 re_wctype_t cc;
2011 switch (cc)
2013 case RECC_ALNUM: return ISALNUM (ch);
2014 case RECC_ALPHA: return ISALPHA (ch);
2015 case RECC_BLANK: return ISBLANK (ch);
2016 case RECC_CNTRL: return ISCNTRL (ch);
2017 case RECC_DIGIT: return ISDIGIT (ch);
2018 case RECC_GRAPH: return ISGRAPH (ch);
2019 case RECC_LOWER: return ISLOWER (ch);
2020 case RECC_PRINT: return ISPRINT (ch);
2021 case RECC_PUNCT: return ISPUNCT (ch);
2022 case RECC_SPACE: return ISSPACE (ch);
2023 case RECC_UPPER: return ISUPPER (ch);
2024 case RECC_XDIGIT: return ISXDIGIT (ch);
2025 case RECC_ASCII: return IS_REAL_ASCII (ch);
2026 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2027 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2028 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2029 case RECC_WORD: return ISWORD (ch);
2030 case RECC_ERROR: return false;
2031 default:
2032 abort();
2036 /* Return a bit-pattern to use in the range-table bits to match multibyte
2037 chars of class CC. */
2038 static int
2039 re_wctype_to_bit (cc)
2040 re_wctype_t cc;
2042 switch (cc)
2044 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2045 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2046 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2047 case RECC_LOWER: return BIT_LOWER;
2048 case RECC_UPPER: return BIT_UPPER;
2049 case RECC_PUNCT: return BIT_PUNCT;
2050 case RECC_SPACE: return BIT_SPACE;
2051 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2052 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2053 default:
2054 abort();
2057 #endif
2059 /* Filling in the work area of a range. */
2061 /* Actually extend the space in WORK_AREA. */
2063 static void
2064 extend_range_table_work_area (work_area)
2065 struct range_table_work_area *work_area;
2067 work_area->allocated += 16 * sizeof (int);
2068 if (work_area->table)
2069 work_area->table
2070 = (int *) realloc (work_area->table, work_area->allocated);
2071 else
2072 work_area->table
2073 = (int *) malloc (work_area->allocated);
2076 #ifdef emacs
2078 /* Carefully find the ranges of codes that are equivalent
2079 under case conversion to the range start..end when passed through
2080 TRANSLATE. Handle the case where non-letters can come in between
2081 two upper-case letters (which happens in Latin-1).
2082 Also handle the case of groups of more than 2 case-equivalent chars.
2084 The basic method is to look at consecutive characters and see
2085 if they can form a run that can be handled as one.
2087 Returns -1 if successful, REG_ESPACE if ran out of space. */
2089 static int
2090 set_image_of_range_1 (work_area, start, end, translate)
2091 RE_TRANSLATE_TYPE translate;
2092 struct range_table_work_area *work_area;
2093 re_wchar_t start, end;
2095 /* `one_case' indicates a character, or a run of characters,
2096 each of which is an isolate (no case-equivalents).
2097 This includes all ASCII non-letters.
2099 `two_case' indicates a character, or a run of characters,
2100 each of which has two case-equivalent forms.
2101 This includes all ASCII letters.
2103 `strange' indicates a character that has more than one
2104 case-equivalent. */
2106 enum case_type {one_case, two_case, strange};
2108 /* Describe the run that is in progress,
2109 which the next character can try to extend.
2110 If run_type is strange, that means there really is no run.
2111 If run_type is one_case, then run_start...run_end is the run.
2112 If run_type is two_case, then the run is run_start...run_end,
2113 and the case-equivalents end at run_eqv_end. */
2115 enum case_type run_type = strange;
2116 int run_start, run_end, run_eqv_end;
2118 Lisp_Object eqv_table;
2120 if (!RE_TRANSLATE_P (translate))
2122 EXTEND_RANGE_TABLE (work_area, 2);
2123 work_area->table[work_area->used++] = (start);
2124 work_area->table[work_area->used++] = (end);
2125 return -1;
2128 eqv_table = XCHAR_TABLE (translate)->extras[2];
2130 for (; start <= end; start++)
2132 enum case_type this_type;
2133 int eqv = RE_TRANSLATE (eqv_table, start);
2134 int minchar, maxchar;
2136 /* Classify this character */
2137 if (eqv == start)
2138 this_type = one_case;
2139 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2140 this_type = two_case;
2141 else
2142 this_type = strange;
2144 if (start < eqv)
2145 minchar = start, maxchar = eqv;
2146 else
2147 minchar = eqv, maxchar = start;
2149 /* Can this character extend the run in progress? */
2150 if (this_type == strange || this_type != run_type
2151 || !(minchar == run_end + 1
2152 && (run_type == two_case
2153 ? maxchar == run_eqv_end + 1 : 1)))
2155 /* No, end the run.
2156 Record each of its equivalent ranges. */
2157 if (run_type == one_case)
2159 EXTEND_RANGE_TABLE (work_area, 2);
2160 work_area->table[work_area->used++] = run_start;
2161 work_area->table[work_area->used++] = run_end;
2163 else if (run_type == two_case)
2165 EXTEND_RANGE_TABLE (work_area, 4);
2166 work_area->table[work_area->used++] = run_start;
2167 work_area->table[work_area->used++] = run_end;
2168 work_area->table[work_area->used++]
2169 = RE_TRANSLATE (eqv_table, run_start);
2170 work_area->table[work_area->used++]
2171 = RE_TRANSLATE (eqv_table, run_end);
2173 run_type = strange;
2176 if (this_type == strange)
2178 /* For a strange character, add each of its equivalents, one
2179 by one. Don't start a range. */
2182 EXTEND_RANGE_TABLE (work_area, 2);
2183 work_area->table[work_area->used++] = eqv;
2184 work_area->table[work_area->used++] = eqv;
2185 eqv = RE_TRANSLATE (eqv_table, eqv);
2187 while (eqv != start);
2190 /* Add this char to the run, or start a new run. */
2191 else if (run_type == strange)
2193 /* Initialize a new range. */
2194 run_type = this_type;
2195 run_start = start;
2196 run_end = start;
2197 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2199 else
2201 /* Extend a running range. */
2202 run_end = minchar;
2203 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2207 /* If a run is still in progress at the end, finish it now
2208 by recording its equivalent ranges. */
2209 if (run_type == one_case)
2211 EXTEND_RANGE_TABLE (work_area, 2);
2212 work_area->table[work_area->used++] = run_start;
2213 work_area->table[work_area->used++] = run_end;
2215 else if (run_type == two_case)
2217 EXTEND_RANGE_TABLE (work_area, 4);
2218 work_area->table[work_area->used++] = run_start;
2219 work_area->table[work_area->used++] = run_end;
2220 work_area->table[work_area->used++]
2221 = RE_TRANSLATE (eqv_table, run_start);
2222 work_area->table[work_area->used++]
2223 = RE_TRANSLATE (eqv_table, run_end);
2226 return -1;
2229 #endif /* emacs */
2231 /* Record the the image of the range start..end when passed through
2232 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2233 and is not even necessarily contiguous.
2234 Normally we approximate it with the smallest contiguous range that contains
2235 all the chars we need. However, for Latin-1 we go to extra effort
2236 to do a better job.
2238 This function is not called for ASCII ranges.
2240 Returns -1 if successful, REG_ESPACE if ran out of space. */
2242 static int
2243 set_image_of_range (work_area, start, end, translate)
2244 RE_TRANSLATE_TYPE translate;
2245 struct range_table_work_area *work_area;
2246 re_wchar_t start, end;
2248 re_wchar_t cmin, cmax;
2250 #ifdef emacs
2251 /* For Latin-1 ranges, use set_image_of_range_1
2252 to get proper handling of ranges that include letters and nonletters.
2253 For a range that includes the whole of Latin-1, this is not necessary.
2254 For other character sets, we don't bother to get this right. */
2255 if (RE_TRANSLATE_P (translate) && start < 04400
2256 && !(start < 04200 && end >= 04377))
2258 int newend;
2259 int tem;
2260 newend = end;
2261 if (newend > 04377)
2262 newend = 04377;
2263 tem = set_image_of_range_1 (work_area, start, newend, translate);
2264 if (tem > 0)
2265 return tem;
2267 start = 04400;
2268 if (end < 04400)
2269 return -1;
2271 #endif
2273 EXTEND_RANGE_TABLE (work_area, 2);
2274 work_area->table[work_area->used++] = (start);
2275 work_area->table[work_area->used++] = (end);
2277 cmin = -1, cmax = -1;
2279 if (RE_TRANSLATE_P (translate))
2281 int ch;
2283 for (ch = start; ch <= end; ch++)
2285 re_wchar_t c = TRANSLATE (ch);
2286 if (! (start <= c && c <= end))
2288 if (cmin == -1)
2289 cmin = c, cmax = c;
2290 else
2292 cmin = MIN (cmin, c);
2293 cmax = MAX (cmax, c);
2298 if (cmin != -1)
2300 EXTEND_RANGE_TABLE (work_area, 2);
2301 work_area->table[work_area->used++] = (cmin);
2302 work_area->table[work_area->used++] = (cmax);
2306 return -1;
2309 #ifndef MATCH_MAY_ALLOCATE
2311 /* If we cannot allocate large objects within re_match_2_internal,
2312 we make the fail stack and register vectors global.
2313 The fail stack, we grow to the maximum size when a regexp
2314 is compiled.
2315 The register vectors, we adjust in size each time we
2316 compile a regexp, according to the number of registers it needs. */
2318 static fail_stack_type fail_stack;
2320 /* Size with which the following vectors are currently allocated.
2321 That is so we can make them bigger as needed,
2322 but never make them smaller. */
2323 static int regs_allocated_size;
2325 static re_char ** regstart, ** regend;
2326 static re_char **best_regstart, **best_regend;
2328 /* Make the register vectors big enough for NUM_REGS registers,
2329 but don't make them smaller. */
2331 static
2332 regex_grow_registers (num_regs)
2333 int num_regs;
2335 if (num_regs > regs_allocated_size)
2337 RETALLOC_IF (regstart, num_regs, re_char *);
2338 RETALLOC_IF (regend, num_regs, re_char *);
2339 RETALLOC_IF (best_regstart, num_regs, re_char *);
2340 RETALLOC_IF (best_regend, num_regs, re_char *);
2342 regs_allocated_size = num_regs;
2346 #endif /* not MATCH_MAY_ALLOCATE */
2348 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2349 compile_stack,
2350 regnum_t regnum));
2352 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2353 Returns one of error codes defined in `regex.h', or zero for success.
2355 Assumes the `allocated' (and perhaps `buffer') and `translate'
2356 fields are set in BUFP on entry.
2358 If it succeeds, results are put in BUFP (if it returns an error, the
2359 contents of BUFP are undefined):
2360 `buffer' is the compiled pattern;
2361 `syntax' is set to SYNTAX;
2362 `used' is set to the length of the compiled pattern;
2363 `fastmap_accurate' is zero;
2364 `re_nsub' is the number of subexpressions in PATTERN;
2365 `not_bol' and `not_eol' are zero;
2367 The `fastmap' field is neither examined nor set. */
2369 /* Insert the `jump' from the end of last alternative to "here".
2370 The space for the jump has already been allocated. */
2371 #define FIXUP_ALT_JUMP() \
2372 do { \
2373 if (fixup_alt_jump) \
2374 STORE_JUMP (jump, fixup_alt_jump, b); \
2375 } while (0)
2378 /* Return, freeing storage we allocated. */
2379 #define FREE_STACK_RETURN(value) \
2380 do { \
2381 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2382 free (compile_stack.stack); \
2383 return value; \
2384 } while (0)
2386 static reg_errcode_t
2387 regex_compile (pattern, size, syntax, bufp)
2388 re_char *pattern;
2389 size_t size;
2390 reg_syntax_t syntax;
2391 struct re_pattern_buffer *bufp;
2393 /* We fetch characters from PATTERN here. */
2394 register re_wchar_t c, c1;
2396 /* A random temporary spot in PATTERN. */
2397 re_char *p1;
2399 /* Points to the end of the buffer, where we should append. */
2400 register unsigned char *b;
2402 /* Keeps track of unclosed groups. */
2403 compile_stack_type compile_stack;
2405 /* Points to the current (ending) position in the pattern. */
2406 #ifdef AIX
2407 /* `const' makes AIX compiler fail. */
2408 unsigned char *p = pattern;
2409 #else
2410 re_char *p = pattern;
2411 #endif
2412 re_char *pend = pattern + size;
2414 /* How to translate the characters in the pattern. */
2415 RE_TRANSLATE_TYPE translate = bufp->translate;
2417 /* Address of the count-byte of the most recently inserted `exactn'
2418 command. This makes it possible to tell if a new exact-match
2419 character can be added to that command or if the character requires
2420 a new `exactn' command. */
2421 unsigned char *pending_exact = 0;
2423 /* Address of start of the most recently finished expression.
2424 This tells, e.g., postfix * where to find the start of its
2425 operand. Reset at the beginning of groups and alternatives. */
2426 unsigned char *laststart = 0;
2428 /* Address of beginning of regexp, or inside of last group. */
2429 unsigned char *begalt;
2431 /* Place in the uncompiled pattern (i.e., the {) to
2432 which to go back if the interval is invalid. */
2433 re_char *beg_interval;
2435 /* Address of the place where a forward jump should go to the end of
2436 the containing expression. Each alternative of an `or' -- except the
2437 last -- ends with a forward jump of this sort. */
2438 unsigned char *fixup_alt_jump = 0;
2440 /* Counts open-groups as they are encountered. Remembered for the
2441 matching close-group on the compile stack, so the same register
2442 number is put in the stop_memory as the start_memory. */
2443 regnum_t regnum = 0;
2445 /* Work area for range table of charset. */
2446 struct range_table_work_area range_table_work;
2448 /* If the object matched can contain multibyte characters. */
2449 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2451 #ifdef DEBUG
2452 debug++;
2453 DEBUG_PRINT1 ("\nCompiling pattern: ");
2454 if (debug > 0)
2456 unsigned debug_count;
2458 for (debug_count = 0; debug_count < size; debug_count++)
2459 putchar (pattern[debug_count]);
2460 putchar ('\n');
2462 #endif /* DEBUG */
2464 /* Initialize the compile stack. */
2465 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2466 if (compile_stack.stack == NULL)
2467 return REG_ESPACE;
2469 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2470 compile_stack.avail = 0;
2472 range_table_work.table = 0;
2473 range_table_work.allocated = 0;
2475 /* Initialize the pattern buffer. */
2476 bufp->syntax = syntax;
2477 bufp->fastmap_accurate = 0;
2478 bufp->not_bol = bufp->not_eol = 0;
2480 /* Set `used' to zero, so that if we return an error, the pattern
2481 printer (for debugging) will think there's no pattern. We reset it
2482 at the end. */
2483 bufp->used = 0;
2485 /* Always count groups, whether or not bufp->no_sub is set. */
2486 bufp->re_nsub = 0;
2488 #if !defined emacs && !defined SYNTAX_TABLE
2489 /* Initialize the syntax table. */
2490 init_syntax_once ();
2491 #endif
2493 if (bufp->allocated == 0)
2495 if (bufp->buffer)
2496 { /* If zero allocated, but buffer is non-null, try to realloc
2497 enough space. This loses if buffer's address is bogus, but
2498 that is the user's responsibility. */
2499 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2501 else
2502 { /* Caller did not allocate a buffer. Do it for them. */
2503 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2505 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2507 bufp->allocated = INIT_BUF_SIZE;
2510 begalt = b = bufp->buffer;
2512 /* Loop through the uncompiled pattern until we're at the end. */
2513 while (p != pend)
2515 PATFETCH (c);
2517 switch (c)
2519 case '^':
2521 if ( /* If at start of pattern, it's an operator. */
2522 p == pattern + 1
2523 /* If context independent, it's an operator. */
2524 || syntax & RE_CONTEXT_INDEP_ANCHORS
2525 /* Otherwise, depends on what's come before. */
2526 || at_begline_loc_p (pattern, p, syntax))
2527 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2528 else
2529 goto normal_char;
2531 break;
2534 case '$':
2536 if ( /* If at end of pattern, it's an operator. */
2537 p == pend
2538 /* If context independent, it's an operator. */
2539 || syntax & RE_CONTEXT_INDEP_ANCHORS
2540 /* Otherwise, depends on what's next. */
2541 || at_endline_loc_p (p, pend, syntax))
2542 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2543 else
2544 goto normal_char;
2546 break;
2549 case '+':
2550 case '?':
2551 if ((syntax & RE_BK_PLUS_QM)
2552 || (syntax & RE_LIMITED_OPS))
2553 goto normal_char;
2554 handle_plus:
2555 case '*':
2556 /* If there is no previous pattern... */
2557 if (!laststart)
2559 if (syntax & RE_CONTEXT_INVALID_OPS)
2560 FREE_STACK_RETURN (REG_BADRPT);
2561 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2562 goto normal_char;
2566 /* 1 means zero (many) matches is allowed. */
2567 boolean zero_times_ok = 0, many_times_ok = 0;
2568 boolean greedy = 1;
2570 /* If there is a sequence of repetition chars, collapse it
2571 down to just one (the right one). We can't combine
2572 interval operators with these because of, e.g., `a{2}*',
2573 which should only match an even number of `a's. */
2575 for (;;)
2577 if ((syntax & RE_FRUGAL)
2578 && c == '?' && (zero_times_ok || many_times_ok))
2579 greedy = 0;
2580 else
2582 zero_times_ok |= c != '+';
2583 many_times_ok |= c != '?';
2586 if (p == pend)
2587 break;
2588 else if (*p == '*'
2589 || (!(syntax & RE_BK_PLUS_QM)
2590 && (*p == '+' || *p == '?')))
2592 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2594 if (p+1 == pend)
2595 FREE_STACK_RETURN (REG_EESCAPE);
2596 if (p[1] == '+' || p[1] == '?')
2597 PATFETCH (c); /* Gobble up the backslash. */
2598 else
2599 break;
2601 else
2602 break;
2603 /* If we get here, we found another repeat character. */
2604 PATFETCH (c);
2607 /* Star, etc. applied to an empty pattern is equivalent
2608 to an empty pattern. */
2609 if (!laststart || laststart == b)
2610 break;
2612 /* Now we know whether or not zero matches is allowed
2613 and also whether or not two or more matches is allowed. */
2614 if (greedy)
2616 if (many_times_ok)
2618 boolean simple = skip_one_char (laststart) == b;
2619 unsigned int startoffset = 0;
2620 re_opcode_t ofj =
2621 /* Check if the loop can match the empty string. */
2622 (simple || !analyse_first (laststart, b, NULL, 0))
2623 ? on_failure_jump : on_failure_jump_loop;
2624 assert (skip_one_char (laststart) <= b);
2626 if (!zero_times_ok && simple)
2627 { /* Since simple * loops can be made faster by using
2628 on_failure_keep_string_jump, we turn simple P+
2629 into PP* if P is simple. */
2630 unsigned char *p1, *p2;
2631 startoffset = b - laststart;
2632 GET_BUFFER_SPACE (startoffset);
2633 p1 = b; p2 = laststart;
2634 while (p2 < p1)
2635 *b++ = *p2++;
2636 zero_times_ok = 1;
2639 GET_BUFFER_SPACE (6);
2640 if (!zero_times_ok)
2641 /* A + loop. */
2642 STORE_JUMP (ofj, b, b + 6);
2643 else
2644 /* Simple * loops can use on_failure_keep_string_jump
2645 depending on what follows. But since we don't know
2646 that yet, we leave the decision up to
2647 on_failure_jump_smart. */
2648 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2649 laststart + startoffset, b + 6);
2650 b += 3;
2651 STORE_JUMP (jump, b, laststart + startoffset);
2652 b += 3;
2654 else
2656 /* A simple ? pattern. */
2657 assert (zero_times_ok);
2658 GET_BUFFER_SPACE (3);
2659 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2660 b += 3;
2663 else /* not greedy */
2664 { /* I wish the greedy and non-greedy cases could be merged. */
2666 GET_BUFFER_SPACE (7); /* We might use less. */
2667 if (many_times_ok)
2669 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2671 /* The non-greedy multiple match looks like
2672 a repeat..until: we only need a conditional jump
2673 at the end of the loop. */
2674 if (emptyp) BUF_PUSH (no_op);
2675 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2676 : on_failure_jump, b, laststart);
2677 b += 3;
2678 if (zero_times_ok)
2680 /* The repeat...until naturally matches one or more.
2681 To also match zero times, we need to first jump to
2682 the end of the loop (its conditional jump). */
2683 INSERT_JUMP (jump, laststart, b);
2684 b += 3;
2687 else
2689 /* non-greedy a?? */
2690 INSERT_JUMP (jump, laststart, b + 3);
2691 b += 3;
2692 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2693 b += 3;
2697 pending_exact = 0;
2698 break;
2701 case '.':
2702 laststart = b;
2703 BUF_PUSH (anychar);
2704 break;
2707 case '[':
2709 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2711 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2713 /* Ensure that we have enough space to push a charset: the
2714 opcode, the length count, and the bitset; 34 bytes in all. */
2715 GET_BUFFER_SPACE (34);
2717 laststart = b;
2719 /* We test `*p == '^' twice, instead of using an if
2720 statement, so we only need one BUF_PUSH. */
2721 BUF_PUSH (*p == '^' ? charset_not : charset);
2722 if (*p == '^')
2723 p++;
2725 /* Remember the first position in the bracket expression. */
2726 p1 = p;
2728 /* Push the number of bytes in the bitmap. */
2729 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2731 /* Clear the whole map. */
2732 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2734 /* charset_not matches newline according to a syntax bit. */
2735 if ((re_opcode_t) b[-2] == charset_not
2736 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2737 SET_LIST_BIT ('\n');
2739 /* Read in characters and ranges, setting map bits. */
2740 for (;;)
2742 boolean escaped_char = false;
2743 const unsigned char *p2 = p;
2745 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2747 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2748 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2749 So the translation is done later in a loop. Example:
2750 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2751 PATFETCH (c);
2753 /* \ might escape characters inside [...] and [^...]. */
2754 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2756 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2758 PATFETCH (c);
2759 escaped_char = true;
2761 else
2763 /* Could be the end of the bracket expression. If it's
2764 not (i.e., when the bracket expression is `[]' so
2765 far), the ']' character bit gets set way below. */
2766 if (c == ']' && p2 != p1)
2767 break;
2770 /* What should we do for the character which is
2771 greater than 0x7F, but not BASE_LEADING_CODE_P?
2772 XXX */
2774 /* See if we're at the beginning of a possible character
2775 class. */
2777 if (!escaped_char &&
2778 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2780 /* Leave room for the null. */
2781 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2782 const unsigned char *class_beg;
2784 PATFETCH (c);
2785 c1 = 0;
2786 class_beg = p;
2788 /* If pattern is `[[:'. */
2789 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2791 for (;;)
2793 PATFETCH (c);
2794 if ((c == ':' && *p == ']') || p == pend)
2795 break;
2796 if (c1 < CHAR_CLASS_MAX_LENGTH)
2797 str[c1++] = c;
2798 else
2799 /* This is in any case an invalid class name. */
2800 str[0] = '\0';
2802 str[c1] = '\0';
2804 /* If isn't a word bracketed by `[:' and `:]':
2805 undo the ending character, the letters, and
2806 leave the leading `:' and `[' (but set bits for
2807 them). */
2808 if (c == ':' && *p == ']')
2810 re_wchar_t ch;
2811 re_wctype_t cc;
2813 cc = re_wctype (str);
2815 if (cc == 0)
2816 FREE_STACK_RETURN (REG_ECTYPE);
2818 /* Throw away the ] at the end of the character
2819 class. */
2820 PATFETCH (c);
2822 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2824 /* Most character classes in a multibyte match
2825 just set a flag. Exceptions are is_blank,
2826 is_digit, is_cntrl, and is_xdigit, since
2827 they can only match ASCII characters. We
2828 don't need to handle them for multibyte.
2829 They are distinguished by a negative wctype. */
2831 if (multibyte)
2832 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2833 re_wctype_to_bit (cc));
2835 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2837 int translated = TRANSLATE (ch);
2838 if (re_iswctype (btowc (ch), cc))
2839 SET_LIST_BIT (translated);
2842 /* Repeat the loop. */
2843 continue;
2845 else
2847 /* Go back to right after the "[:". */
2848 p = class_beg;
2849 SET_LIST_BIT ('[');
2851 /* Because the `:' may starts the range, we
2852 can't simply set bit and repeat the loop.
2853 Instead, just set it to C and handle below. */
2854 c = ':';
2858 if (p < pend && p[0] == '-' && p[1] != ']')
2861 /* Discard the `-'. */
2862 PATFETCH (c1);
2864 /* Fetch the character which ends the range. */
2865 PATFETCH (c1);
2867 if (SINGLE_BYTE_CHAR_P (c))
2869 if (! SINGLE_BYTE_CHAR_P (c1))
2871 /* Handle a range starting with a
2872 character of less than 256, and ending
2873 with a character of not less than 256.
2874 Split that into two ranges, the low one
2875 ending at 0377, and the high one
2876 starting at the smallest character in
2877 the charset of C1 and ending at C1. */
2878 int charset = CHAR_CHARSET (c1);
2879 re_wchar_t c2 = MAKE_CHAR (charset, 0, 0);
2881 SET_RANGE_TABLE_WORK_AREA (range_table_work,
2882 c2, c1);
2883 c1 = 0377;
2886 else if (!SAME_CHARSET_P (c, c1))
2887 FREE_STACK_RETURN (REG_ERANGE);
2889 else
2890 /* Range from C to C. */
2891 c1 = c;
2893 /* Set the range ... */
2894 if (SINGLE_BYTE_CHAR_P (c))
2895 /* ... into bitmap. */
2897 re_wchar_t this_char;
2898 re_wchar_t range_start = c, range_end = c1;
2900 /* If the start is after the end, the range is empty. */
2901 if (range_start > range_end)
2903 if (syntax & RE_NO_EMPTY_RANGES)
2904 FREE_STACK_RETURN (REG_ERANGE);
2905 /* Else, repeat the loop. */
2907 else
2909 for (this_char = range_start; this_char <= range_end;
2910 this_char++)
2911 SET_LIST_BIT (TRANSLATE (this_char));
2914 else
2915 /* ... into range table. */
2916 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2919 /* Discard any (non)matching list bytes that are all 0 at the
2920 end of the map. Decrease the map-length byte too. */
2921 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2922 b[-1]--;
2923 b += b[-1];
2925 /* Build real range table from work area. */
2926 if (RANGE_TABLE_WORK_USED (range_table_work)
2927 || RANGE_TABLE_WORK_BITS (range_table_work))
2929 int i;
2930 int used = RANGE_TABLE_WORK_USED (range_table_work);
2932 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2933 bytes for flags, two for COUNT, and three bytes for
2934 each character. */
2935 GET_BUFFER_SPACE (4 + used * 3);
2937 /* Indicate the existence of range table. */
2938 laststart[1] |= 0x80;
2940 /* Store the character class flag bits into the range table.
2941 If not in emacs, these flag bits are always 0. */
2942 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2943 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2945 STORE_NUMBER_AND_INCR (b, used / 2);
2946 for (i = 0; i < used; i++)
2947 STORE_CHARACTER_AND_INCR
2948 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2951 break;
2954 case '(':
2955 if (syntax & RE_NO_BK_PARENS)
2956 goto handle_open;
2957 else
2958 goto normal_char;
2961 case ')':
2962 if (syntax & RE_NO_BK_PARENS)
2963 goto handle_close;
2964 else
2965 goto normal_char;
2968 case '\n':
2969 if (syntax & RE_NEWLINE_ALT)
2970 goto handle_alt;
2971 else
2972 goto normal_char;
2975 case '|':
2976 if (syntax & RE_NO_BK_VBAR)
2977 goto handle_alt;
2978 else
2979 goto normal_char;
2982 case '{':
2983 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2984 goto handle_interval;
2985 else
2986 goto normal_char;
2989 case '\\':
2990 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2992 /* Do not translate the character after the \, so that we can
2993 distinguish, e.g., \B from \b, even if we normally would
2994 translate, e.g., B to b. */
2995 PATFETCH (c);
2997 switch (c)
2999 case '(':
3000 if (syntax & RE_NO_BK_PARENS)
3001 goto normal_backslash;
3003 handle_open:
3005 int shy = 0;
3006 if (p+1 < pend)
3008 /* Look for a special (?...) construct */
3009 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3011 PATFETCH (c); /* Gobble up the '?'. */
3012 PATFETCH (c);
3013 switch (c)
3015 case ':': shy = 1; break;
3016 default:
3017 /* Only (?:...) is supported right now. */
3018 FREE_STACK_RETURN (REG_BADPAT);
3023 if (!shy)
3025 bufp->re_nsub++;
3026 regnum++;
3029 if (COMPILE_STACK_FULL)
3031 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3032 compile_stack_elt_t);
3033 if (compile_stack.stack == NULL) return REG_ESPACE;
3035 compile_stack.size <<= 1;
3038 /* These are the values to restore when we hit end of this
3039 group. They are all relative offsets, so that if the
3040 whole pattern moves because of realloc, they will still
3041 be valid. */
3042 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3043 COMPILE_STACK_TOP.fixup_alt_jump
3044 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3045 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3046 COMPILE_STACK_TOP.regnum = shy ? -regnum : regnum;
3048 /* Do not push a
3049 start_memory for groups beyond the last one we can
3050 represent in the compiled pattern. */
3051 if (regnum <= MAX_REGNUM && !shy)
3052 BUF_PUSH_2 (start_memory, regnum);
3054 compile_stack.avail++;
3056 fixup_alt_jump = 0;
3057 laststart = 0;
3058 begalt = b;
3059 /* If we've reached MAX_REGNUM groups, then this open
3060 won't actually generate any code, so we'll have to
3061 clear pending_exact explicitly. */
3062 pending_exact = 0;
3063 break;
3066 case ')':
3067 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3069 if (COMPILE_STACK_EMPTY)
3071 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3072 goto normal_backslash;
3073 else
3074 FREE_STACK_RETURN (REG_ERPAREN);
3077 handle_close:
3078 FIXUP_ALT_JUMP ();
3080 /* See similar code for backslashed left paren above. */
3081 if (COMPILE_STACK_EMPTY)
3083 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3084 goto normal_char;
3085 else
3086 FREE_STACK_RETURN (REG_ERPAREN);
3089 /* Since we just checked for an empty stack above, this
3090 ``can't happen''. */
3091 assert (compile_stack.avail != 0);
3093 /* We don't just want to restore into `regnum', because
3094 later groups should continue to be numbered higher,
3095 as in `(ab)c(de)' -- the second group is #2. */
3096 regnum_t this_group_regnum;
3098 compile_stack.avail--;
3099 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3100 fixup_alt_jump
3101 = COMPILE_STACK_TOP.fixup_alt_jump
3102 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3103 : 0;
3104 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3105 this_group_regnum = COMPILE_STACK_TOP.regnum;
3106 /* If we've reached MAX_REGNUM groups, then this open
3107 won't actually generate any code, so we'll have to
3108 clear pending_exact explicitly. */
3109 pending_exact = 0;
3111 /* We're at the end of the group, so now we know how many
3112 groups were inside this one. */
3113 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
3114 BUF_PUSH_2 (stop_memory, this_group_regnum);
3116 break;
3119 case '|': /* `\|'. */
3120 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3121 goto normal_backslash;
3122 handle_alt:
3123 if (syntax & RE_LIMITED_OPS)
3124 goto normal_char;
3126 /* Insert before the previous alternative a jump which
3127 jumps to this alternative if the former fails. */
3128 GET_BUFFER_SPACE (3);
3129 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3130 pending_exact = 0;
3131 b += 3;
3133 /* The alternative before this one has a jump after it
3134 which gets executed if it gets matched. Adjust that
3135 jump so it will jump to this alternative's analogous
3136 jump (put in below, which in turn will jump to the next
3137 (if any) alternative's such jump, etc.). The last such
3138 jump jumps to the correct final destination. A picture:
3139 _____ _____
3140 | | | |
3141 | v | v
3142 a | b | c
3144 If we are at `b', then fixup_alt_jump right now points to a
3145 three-byte space after `a'. We'll put in the jump, set
3146 fixup_alt_jump to right after `b', and leave behind three
3147 bytes which we'll fill in when we get to after `c'. */
3149 FIXUP_ALT_JUMP ();
3151 /* Mark and leave space for a jump after this alternative,
3152 to be filled in later either by next alternative or
3153 when know we're at the end of a series of alternatives. */
3154 fixup_alt_jump = b;
3155 GET_BUFFER_SPACE (3);
3156 b += 3;
3158 laststart = 0;
3159 begalt = b;
3160 break;
3163 case '{':
3164 /* If \{ is a literal. */
3165 if (!(syntax & RE_INTERVALS)
3166 /* If we're at `\{' and it's not the open-interval
3167 operator. */
3168 || (syntax & RE_NO_BK_BRACES))
3169 goto normal_backslash;
3171 handle_interval:
3173 /* If got here, then the syntax allows intervals. */
3175 /* At least (most) this many matches must be made. */
3176 int lower_bound = 0, upper_bound = -1;
3178 beg_interval = p;
3180 if (p == pend)
3181 FREE_STACK_RETURN (REG_EBRACE);
3183 GET_UNSIGNED_NUMBER (lower_bound);
3185 if (c == ',')
3186 GET_UNSIGNED_NUMBER (upper_bound);
3187 else
3188 /* Interval such as `{1}' => match exactly once. */
3189 upper_bound = lower_bound;
3191 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3192 || (upper_bound >= 0 && lower_bound > upper_bound))
3193 FREE_STACK_RETURN (REG_BADBR);
3195 if (!(syntax & RE_NO_BK_BRACES))
3197 if (c != '\\')
3198 FREE_STACK_RETURN (REG_BADBR);
3200 PATFETCH (c);
3203 if (c != '}')
3204 FREE_STACK_RETURN (REG_BADBR);
3206 /* We just parsed a valid interval. */
3208 /* If it's invalid to have no preceding re. */
3209 if (!laststart)
3211 if (syntax & RE_CONTEXT_INVALID_OPS)
3212 FREE_STACK_RETURN (REG_BADRPT);
3213 else if (syntax & RE_CONTEXT_INDEP_OPS)
3214 laststart = b;
3215 else
3216 goto unfetch_interval;
3219 if (upper_bound == 0)
3220 /* If the upper bound is zero, just drop the sub pattern
3221 altogether. */
3222 b = laststart;
3223 else if (lower_bound == 1 && upper_bound == 1)
3224 /* Just match it once: nothing to do here. */
3227 /* Otherwise, we have a nontrivial interval. When
3228 we're all done, the pattern will look like:
3229 set_number_at <jump count> <upper bound>
3230 set_number_at <succeed_n count> <lower bound>
3231 succeed_n <after jump addr> <succeed_n count>
3232 <body of loop>
3233 jump_n <succeed_n addr> <jump count>
3234 (The upper bound and `jump_n' are omitted if
3235 `upper_bound' is 1, though.) */
3236 else
3237 { /* If the upper bound is > 1, we need to insert
3238 more at the end of the loop. */
3239 unsigned int nbytes = (upper_bound < 0 ? 3
3240 : upper_bound > 1 ? 5 : 0);
3241 unsigned int startoffset = 0;
3243 GET_BUFFER_SPACE (20); /* We might use less. */
3245 if (lower_bound == 0)
3247 /* A succeed_n that starts with 0 is really a
3248 a simple on_failure_jump_loop. */
3249 INSERT_JUMP (on_failure_jump_loop, laststart,
3250 b + 3 + nbytes);
3251 b += 3;
3253 else
3255 /* Initialize lower bound of the `succeed_n', even
3256 though it will be set during matching by its
3257 attendant `set_number_at' (inserted next),
3258 because `re_compile_fastmap' needs to know.
3259 Jump to the `jump_n' we might insert below. */
3260 INSERT_JUMP2 (succeed_n, laststart,
3261 b + 5 + nbytes,
3262 lower_bound);
3263 b += 5;
3265 /* Code to initialize the lower bound. Insert
3266 before the `succeed_n'. The `5' is the last two
3267 bytes of this `set_number_at', plus 3 bytes of
3268 the following `succeed_n'. */
3269 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3270 b += 5;
3271 startoffset += 5;
3274 if (upper_bound < 0)
3276 /* A negative upper bound stands for infinity,
3277 in which case it degenerates to a plain jump. */
3278 STORE_JUMP (jump, b, laststart + startoffset);
3279 b += 3;
3281 else if (upper_bound > 1)
3282 { /* More than one repetition is allowed, so
3283 append a backward jump to the `succeed_n'
3284 that starts this interval.
3286 When we've reached this during matching,
3287 we'll have matched the interval once, so
3288 jump back only `upper_bound - 1' times. */
3289 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3290 upper_bound - 1);
3291 b += 5;
3293 /* The location we want to set is the second
3294 parameter of the `jump_n'; that is `b-2' as
3295 an absolute address. `laststart' will be
3296 the `set_number_at' we're about to insert;
3297 `laststart+3' the number to set, the source
3298 for the relative address. But we are
3299 inserting into the middle of the pattern --
3300 so everything is getting moved up by 5.
3301 Conclusion: (b - 2) - (laststart + 3) + 5,
3302 i.e., b - laststart.
3304 We insert this at the beginning of the loop
3305 so that if we fail during matching, we'll
3306 reinitialize the bounds. */
3307 insert_op2 (set_number_at, laststart, b - laststart,
3308 upper_bound - 1, b);
3309 b += 5;
3312 pending_exact = 0;
3313 beg_interval = NULL;
3315 break;
3317 unfetch_interval:
3318 /* If an invalid interval, match the characters as literals. */
3319 assert (beg_interval);
3320 p = beg_interval;
3321 beg_interval = NULL;
3323 /* normal_char and normal_backslash need `c'. */
3324 c = '{';
3326 if (!(syntax & RE_NO_BK_BRACES))
3328 assert (p > pattern && p[-1] == '\\');
3329 goto normal_backslash;
3331 else
3332 goto normal_char;
3334 #ifdef emacs
3335 /* There is no way to specify the before_dot and after_dot
3336 operators. rms says this is ok. --karl */
3337 case '=':
3338 BUF_PUSH (at_dot);
3339 break;
3341 case 's':
3342 laststart = b;
3343 PATFETCH (c);
3344 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3345 break;
3347 case 'S':
3348 laststart = b;
3349 PATFETCH (c);
3350 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3351 break;
3353 case 'c':
3354 laststart = b;
3355 PATFETCH (c);
3356 BUF_PUSH_2 (categoryspec, c);
3357 break;
3359 case 'C':
3360 laststart = b;
3361 PATFETCH (c);
3362 BUF_PUSH_2 (notcategoryspec, c);
3363 break;
3364 #endif /* emacs */
3367 case 'w':
3368 if (syntax & RE_NO_GNU_OPS)
3369 goto normal_char;
3370 laststart = b;
3371 BUF_PUSH_2 (syntaxspec, Sword);
3372 break;
3375 case 'W':
3376 if (syntax & RE_NO_GNU_OPS)
3377 goto normal_char;
3378 laststart = b;
3379 BUF_PUSH_2 (notsyntaxspec, Sword);
3380 break;
3383 case '<':
3384 if (syntax & RE_NO_GNU_OPS)
3385 goto normal_char;
3386 BUF_PUSH (wordbeg);
3387 break;
3389 case '>':
3390 if (syntax & RE_NO_GNU_OPS)
3391 goto normal_char;
3392 BUF_PUSH (wordend);
3393 break;
3395 case 'b':
3396 if (syntax & RE_NO_GNU_OPS)
3397 goto normal_char;
3398 BUF_PUSH (wordbound);
3399 break;
3401 case 'B':
3402 if (syntax & RE_NO_GNU_OPS)
3403 goto normal_char;
3404 BUF_PUSH (notwordbound);
3405 break;
3407 case '`':
3408 if (syntax & RE_NO_GNU_OPS)
3409 goto normal_char;
3410 BUF_PUSH (begbuf);
3411 break;
3413 case '\'':
3414 if (syntax & RE_NO_GNU_OPS)
3415 goto normal_char;
3416 BUF_PUSH (endbuf);
3417 break;
3419 case '1': case '2': case '3': case '4': case '5':
3420 case '6': case '7': case '8': case '9':
3422 regnum_t reg;
3424 if (syntax & RE_NO_BK_REFS)
3425 goto normal_backslash;
3427 reg = c - '0';
3429 /* Can't back reference to a subexpression before its end. */
3430 if (reg > regnum || group_in_compile_stack (compile_stack, reg))
3431 FREE_STACK_RETURN (REG_ESUBREG);
3433 laststart = b;
3434 BUF_PUSH_2 (duplicate, reg);
3436 break;
3439 case '+':
3440 case '?':
3441 if (syntax & RE_BK_PLUS_QM)
3442 goto handle_plus;
3443 else
3444 goto normal_backslash;
3446 default:
3447 normal_backslash:
3448 /* You might think it would be useful for \ to mean
3449 not to translate; but if we don't translate it
3450 it will never match anything. */
3451 goto normal_char;
3453 break;
3456 default:
3457 /* Expects the character in `c'. */
3458 normal_char:
3459 /* If no exactn currently being built. */
3460 if (!pending_exact
3462 /* If last exactn not at current position. */
3463 || pending_exact + *pending_exact + 1 != b
3465 /* We have only one byte following the exactn for the count. */
3466 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3468 /* If followed by a repetition operator. */
3469 || (p != pend && (*p == '*' || *p == '^'))
3470 || ((syntax & RE_BK_PLUS_QM)
3471 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3472 : p != pend && (*p == '+' || *p == '?'))
3473 || ((syntax & RE_INTERVALS)
3474 && ((syntax & RE_NO_BK_BRACES)
3475 ? p != pend && *p == '{'
3476 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3478 /* Start building a new exactn. */
3480 laststart = b;
3482 BUF_PUSH_2 (exactn, 0);
3483 pending_exact = b - 1;
3486 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3488 int len;
3490 c = TRANSLATE (c);
3491 if (multibyte)
3492 len = CHAR_STRING (c, b);
3493 else
3494 *b = c, len = 1;
3495 b += len;
3496 (*pending_exact) += len;
3499 break;
3500 } /* switch (c) */
3501 } /* while p != pend */
3504 /* Through the pattern now. */
3506 FIXUP_ALT_JUMP ();
3508 if (!COMPILE_STACK_EMPTY)
3509 FREE_STACK_RETURN (REG_EPAREN);
3511 /* If we don't want backtracking, force success
3512 the first time we reach the end of the compiled pattern. */
3513 if (syntax & RE_NO_POSIX_BACKTRACKING)
3514 BUF_PUSH (succeed);
3516 free (compile_stack.stack);
3518 /* We have succeeded; set the length of the buffer. */
3519 bufp->used = b - bufp->buffer;
3521 #ifdef DEBUG
3522 if (debug > 0)
3524 re_compile_fastmap (bufp);
3525 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3526 print_compiled_pattern (bufp);
3528 debug--;
3529 #endif /* DEBUG */
3531 #ifndef MATCH_MAY_ALLOCATE
3532 /* Initialize the failure stack to the largest possible stack. This
3533 isn't necessary unless we're trying to avoid calling alloca in
3534 the search and match routines. */
3536 int num_regs = bufp->re_nsub + 1;
3538 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3540 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3542 if (! fail_stack.stack)
3543 fail_stack.stack
3544 = (fail_stack_elt_t *) malloc (fail_stack.size
3545 * sizeof (fail_stack_elt_t));
3546 else
3547 fail_stack.stack
3548 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3549 (fail_stack.size
3550 * sizeof (fail_stack_elt_t)));
3553 regex_grow_registers (num_regs);
3555 #endif /* not MATCH_MAY_ALLOCATE */
3557 return REG_NOERROR;
3558 } /* regex_compile */
3560 /* Subroutines for `regex_compile'. */
3562 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3564 static void
3565 store_op1 (op, loc, arg)
3566 re_opcode_t op;
3567 unsigned char *loc;
3568 int arg;
3570 *loc = (unsigned char) op;
3571 STORE_NUMBER (loc + 1, arg);
3575 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3577 static void
3578 store_op2 (op, loc, arg1, arg2)
3579 re_opcode_t op;
3580 unsigned char *loc;
3581 int arg1, arg2;
3583 *loc = (unsigned char) op;
3584 STORE_NUMBER (loc + 1, arg1);
3585 STORE_NUMBER (loc + 3, arg2);
3589 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3590 for OP followed by two-byte integer parameter ARG. */
3592 static void
3593 insert_op1 (op, loc, arg, end)
3594 re_opcode_t op;
3595 unsigned char *loc;
3596 int arg;
3597 unsigned char *end;
3599 register unsigned char *pfrom = end;
3600 register unsigned char *pto = end + 3;
3602 while (pfrom != loc)
3603 *--pto = *--pfrom;
3605 store_op1 (op, loc, arg);
3609 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3611 static void
3612 insert_op2 (op, loc, arg1, arg2, end)
3613 re_opcode_t op;
3614 unsigned char *loc;
3615 int arg1, arg2;
3616 unsigned char *end;
3618 register unsigned char *pfrom = end;
3619 register unsigned char *pto = end + 5;
3621 while (pfrom != loc)
3622 *--pto = *--pfrom;
3624 store_op2 (op, loc, arg1, arg2);
3628 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3629 after an alternative or a begin-subexpression. We assume there is at
3630 least one character before the ^. */
3632 static boolean
3633 at_begline_loc_p (pattern, p, syntax)
3634 re_char *pattern, *p;
3635 reg_syntax_t syntax;
3637 re_char *prev = p - 2;
3638 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3640 return
3641 /* After a subexpression? */
3642 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3643 /* After an alternative? */
3644 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3645 /* After a shy subexpression? */
3646 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3647 && prev[-1] == '?' && prev[-2] == '('
3648 && (syntax & RE_NO_BK_PARENS
3649 || (prev - 3 >= pattern && prev[-3] == '\\')));
3653 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3654 at least one character after the $, i.e., `P < PEND'. */
3656 static boolean
3657 at_endline_loc_p (p, pend, syntax)
3658 re_char *p, *pend;
3659 reg_syntax_t syntax;
3661 re_char *next = p;
3662 boolean next_backslash = *next == '\\';
3663 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3665 return
3666 /* Before a subexpression? */
3667 (syntax & RE_NO_BK_PARENS ? *next == ')'
3668 : next_backslash && next_next && *next_next == ')')
3669 /* Before an alternative? */
3670 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3671 : next_backslash && next_next && *next_next == '|');
3675 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3676 false if it's not. */
3678 static boolean
3679 group_in_compile_stack (compile_stack, regnum)
3680 compile_stack_type compile_stack;
3681 regnum_t regnum;
3683 int this_element;
3685 for (this_element = compile_stack.avail - 1;
3686 this_element >= 0;
3687 this_element--)
3688 if (compile_stack.stack[this_element].regnum == regnum)
3689 return true;
3691 return false;
3694 /* analyse_first.
3695 If fastmap is non-NULL, go through the pattern and fill fastmap
3696 with all the possible leading chars. If fastmap is NULL, don't
3697 bother filling it up (obviously) and only return whether the
3698 pattern could potentially match the empty string.
3700 Return 1 if p..pend might match the empty string.
3701 Return 0 if p..pend matches at least one char.
3702 Return -1 if fastmap was not updated accurately. */
3704 static int
3705 analyse_first (p, pend, fastmap, multibyte)
3706 re_char *p, *pend;
3707 char *fastmap;
3708 const int multibyte;
3710 int j, k;
3711 boolean not;
3713 /* If all elements for base leading-codes in fastmap is set, this
3714 flag is set true. */
3715 boolean match_any_multibyte_characters = false;
3717 assert (p);
3719 /* The loop below works as follows:
3720 - It has a working-list kept in the PATTERN_STACK and which basically
3721 starts by only containing a pointer to the first operation.
3722 - If the opcode we're looking at is a match against some set of
3723 chars, then we add those chars to the fastmap and go on to the
3724 next work element from the worklist (done via `break').
3725 - If the opcode is a control operator on the other hand, we either
3726 ignore it (if it's meaningless at this point, such as `start_memory')
3727 or execute it (if it's a jump). If the jump has several destinations
3728 (i.e. `on_failure_jump'), then we push the other destination onto the
3729 worklist.
3730 We guarantee termination by ignoring backward jumps (more or less),
3731 so that `p' is monotonically increasing. More to the point, we
3732 never set `p' (or push) anything `<= p1'. */
3734 while (p < pend)
3736 /* `p1' is used as a marker of how far back a `on_failure_jump'
3737 can go without being ignored. It is normally equal to `p'
3738 (which prevents any backward `on_failure_jump') except right
3739 after a plain `jump', to allow patterns such as:
3740 0: jump 10
3741 3..9: <body>
3742 10: on_failure_jump 3
3743 as used for the *? operator. */
3744 re_char *p1 = p;
3746 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3748 case succeed:
3749 return 1;
3750 continue;
3752 case duplicate:
3753 /* If the first character has to match a backreference, that means
3754 that the group was empty (since it already matched). Since this
3755 is the only case that interests us here, we can assume that the
3756 backreference must match the empty string. */
3757 p++;
3758 continue;
3761 /* Following are the cases which match a character. These end
3762 with `break'. */
3764 case exactn:
3765 if (fastmap)
3767 int c = RE_STRING_CHAR (p + 1, pend - p);
3769 if (SINGLE_BYTE_CHAR_P (c))
3770 fastmap[c] = 1;
3771 else
3772 fastmap[p[1]] = 1;
3774 break;
3777 case anychar:
3778 /* We could put all the chars except for \n (and maybe \0)
3779 but we don't bother since it is generally not worth it. */
3780 if (!fastmap) break;
3781 return -1;
3784 case charset_not:
3785 /* Chars beyond end of bitmap are possible matches.
3786 All the single-byte codes can occur in multibyte buffers.
3787 So any that are not listed in the charset
3788 are possible matches, even in multibyte buffers. */
3789 if (!fastmap) break;
3790 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3791 j < (1 << BYTEWIDTH); j++)
3792 fastmap[j] = 1;
3793 /* Fallthrough */
3794 case charset:
3795 if (!fastmap) break;
3796 not = (re_opcode_t) *(p - 1) == charset_not;
3797 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3798 j >= 0; j--)
3799 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3800 fastmap[j] = 1;
3802 if ((not && multibyte)
3803 /* Any character set can possibly contain a character
3804 which doesn't match the specified set of characters. */
3805 || (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3806 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3807 /* If we can match a character class, we can match
3808 any character set. */
3810 set_fastmap_for_multibyte_characters:
3811 if (match_any_multibyte_characters == false)
3813 for (j = 0x80; j < 0xA0; j++) /* XXX */
3814 if (BASE_LEADING_CODE_P (j))
3815 fastmap[j] = 1;
3816 match_any_multibyte_characters = true;
3820 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3821 && match_any_multibyte_characters == false)
3823 /* Set fastmap[I] 1 where I is a base leading code of each
3824 multibyte character in the range table. */
3825 int c, count;
3827 /* Make P points the range table. `+ 2' is to skip flag
3828 bits for a character class. */
3829 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3831 /* Extract the number of ranges in range table into COUNT. */
3832 EXTRACT_NUMBER_AND_INCR (count, p);
3833 for (; count > 0; count--, p += 2 * 3) /* XXX */
3835 /* Extract the start of each range. */
3836 EXTRACT_CHARACTER (c, p);
3837 j = CHAR_CHARSET (c);
3838 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3841 break;
3843 case syntaxspec:
3844 case notsyntaxspec:
3845 if (!fastmap) break;
3846 #ifndef emacs
3847 not = (re_opcode_t)p[-1] == notsyntaxspec;
3848 k = *p++;
3849 for (j = 0; j < (1 << BYTEWIDTH); j++)
3850 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3851 fastmap[j] = 1;
3852 break;
3853 #else /* emacs */
3854 /* This match depends on text properties. These end with
3855 aborting optimizations. */
3856 return -1;
3858 case categoryspec:
3859 case notcategoryspec:
3860 if (!fastmap) break;
3861 not = (re_opcode_t)p[-1] == notcategoryspec;
3862 k = *p++;
3863 for (j = 0; j < (1 << BYTEWIDTH); j++)
3864 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3865 fastmap[j] = 1;
3867 if (multibyte)
3868 /* Any character set can possibly contain a character
3869 whose category is K (or not). */
3870 goto set_fastmap_for_multibyte_characters;
3871 break;
3873 /* All cases after this match the empty string. These end with
3874 `continue'. */
3876 case before_dot:
3877 case at_dot:
3878 case after_dot:
3879 #endif /* !emacs */
3880 case no_op:
3881 case begline:
3882 case endline:
3883 case begbuf:
3884 case endbuf:
3885 case wordbound:
3886 case notwordbound:
3887 case wordbeg:
3888 case wordend:
3889 continue;
3892 case jump:
3893 EXTRACT_NUMBER_AND_INCR (j, p);
3894 if (j < 0)
3895 /* Backward jumps can only go back to code that we've already
3896 visited. `re_compile' should make sure this is true. */
3897 break;
3898 p += j;
3899 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3901 case on_failure_jump:
3902 case on_failure_keep_string_jump:
3903 case on_failure_jump_loop:
3904 case on_failure_jump_nastyloop:
3905 case on_failure_jump_smart:
3906 p++;
3907 break;
3908 default:
3909 continue;
3911 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3912 to jump back to "just after here". */
3913 /* Fallthrough */
3915 case on_failure_jump:
3916 case on_failure_keep_string_jump:
3917 case on_failure_jump_nastyloop:
3918 case on_failure_jump_loop:
3919 case on_failure_jump_smart:
3920 EXTRACT_NUMBER_AND_INCR (j, p);
3921 if (p + j <= p1)
3922 ; /* Backward jump to be ignored. */
3923 else
3924 { /* We have to look down both arms.
3925 We first go down the "straight" path so as to minimize
3926 stack usage when going through alternatives. */
3927 int r = analyse_first (p, pend, fastmap, multibyte);
3928 if (r) return r;
3929 p += j;
3931 continue;
3934 case jump_n:
3935 /* This code simply does not properly handle forward jump_n. */
3936 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
3937 p += 4;
3938 /* jump_n can either jump or fall through. The (backward) jump
3939 case has already been handled, so we only need to look at the
3940 fallthrough case. */
3941 continue;
3943 case succeed_n:
3944 /* If N == 0, it should be an on_failure_jump_loop instead. */
3945 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
3946 p += 4;
3947 /* We only care about one iteration of the loop, so we don't
3948 need to consider the case where this behaves like an
3949 on_failure_jump. */
3950 continue;
3953 case set_number_at:
3954 p += 4;
3955 continue;
3958 case start_memory:
3959 case stop_memory:
3960 p += 1;
3961 continue;
3964 default:
3965 abort (); /* We have listed all the cases. */
3966 } /* switch *p++ */
3968 /* Getting here means we have found the possible starting
3969 characters for one path of the pattern -- and that the empty
3970 string does not match. We need not follow this path further. */
3971 return 0;
3972 } /* while p */
3974 /* We reached the end without matching anything. */
3975 return 1;
3977 } /* analyse_first */
3979 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3980 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3981 characters can start a string that matches the pattern. This fastmap
3982 is used by re_search to skip quickly over impossible starting points.
3984 Character codes above (1 << BYTEWIDTH) are not represented in the
3985 fastmap, but the leading codes are represented. Thus, the fastmap
3986 indicates which character sets could start a match.
3988 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3989 area as BUFP->fastmap.
3991 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3992 the pattern buffer.
3994 Returns 0 if we succeed, -2 if an internal error. */
3997 re_compile_fastmap (bufp)
3998 struct re_pattern_buffer *bufp;
4000 char *fastmap = bufp->fastmap;
4001 int analysis;
4003 assert (fastmap && bufp->buffer);
4005 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4006 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4008 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4009 fastmap, RE_MULTIBYTE_P (bufp));
4010 bufp->can_be_null = (analysis != 0);
4011 return 0;
4012 } /* re_compile_fastmap */
4014 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4015 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4016 this memory for recording register information. STARTS and ENDS
4017 must be allocated using the malloc library routine, and must each
4018 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4020 If NUM_REGS == 0, then subsequent matches should allocate their own
4021 register data.
4023 Unless this function is called, the first search or match using
4024 PATTERN_BUFFER will allocate its own register data, without
4025 freeing the old data. */
4027 void
4028 re_set_registers (bufp, regs, num_regs, starts, ends)
4029 struct re_pattern_buffer *bufp;
4030 struct re_registers *regs;
4031 unsigned num_regs;
4032 regoff_t *starts, *ends;
4034 if (num_regs)
4036 bufp->regs_allocated = REGS_REALLOCATE;
4037 regs->num_regs = num_regs;
4038 regs->start = starts;
4039 regs->end = ends;
4041 else
4043 bufp->regs_allocated = REGS_UNALLOCATED;
4044 regs->num_regs = 0;
4045 regs->start = regs->end = (regoff_t *) 0;
4048 WEAK_ALIAS (__re_set_registers, re_set_registers)
4050 /* Searching routines. */
4052 /* Like re_search_2, below, but only one string is specified, and
4053 doesn't let you say where to stop matching. */
4056 re_search (bufp, string, size, startpos, range, regs)
4057 struct re_pattern_buffer *bufp;
4058 const char *string;
4059 int size, startpos, range;
4060 struct re_registers *regs;
4062 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4063 regs, size);
4065 WEAK_ALIAS (__re_search, re_search)
4067 /* End address of virtual concatenation of string. */
4068 #define STOP_ADDR_VSTRING(P) \
4069 (((P) >= size1 ? string2 + size2 : string1 + size1))
4071 /* Address of POS in the concatenation of virtual string. */
4072 #define POS_ADDR_VSTRING(POS) \
4073 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4075 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4076 virtual concatenation of STRING1 and STRING2, starting first at index
4077 STARTPOS, then at STARTPOS + 1, and so on.
4079 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4081 RANGE is how far to scan while trying to match. RANGE = 0 means try
4082 only at STARTPOS; in general, the last start tried is STARTPOS +
4083 RANGE.
4085 In REGS, return the indices of the virtual concatenation of STRING1
4086 and STRING2 that matched the entire BUFP->buffer and its contained
4087 subexpressions.
4089 Do not consider matching one past the index STOP in the virtual
4090 concatenation of STRING1 and STRING2.
4092 We return either the position in the strings at which the match was
4093 found, -1 if no match, or -2 if error (such as failure
4094 stack overflow). */
4097 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
4098 struct re_pattern_buffer *bufp;
4099 const char *str1, *str2;
4100 int size1, size2;
4101 int startpos;
4102 int range;
4103 struct re_registers *regs;
4104 int stop;
4106 int val;
4107 re_char *string1 = (re_char*) str1;
4108 re_char *string2 = (re_char*) str2;
4109 register char *fastmap = bufp->fastmap;
4110 register RE_TRANSLATE_TYPE translate = bufp->translate;
4111 int total_size = size1 + size2;
4112 int endpos = startpos + range;
4113 boolean anchored_start;
4115 /* Nonzero if we have to concern multibyte character. */
4116 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4118 /* Check for out-of-range STARTPOS. */
4119 if (startpos < 0 || startpos > total_size)
4120 return -1;
4122 /* Fix up RANGE if it might eventually take us outside
4123 the virtual concatenation of STRING1 and STRING2.
4124 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4125 if (endpos < 0)
4126 range = 0 - startpos;
4127 else if (endpos > total_size)
4128 range = total_size - startpos;
4130 /* If the search isn't to be a backwards one, don't waste time in a
4131 search for a pattern anchored at beginning of buffer. */
4132 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4134 if (startpos > 0)
4135 return -1;
4136 else
4137 range = 0;
4140 #ifdef emacs
4141 /* In a forward search for something that starts with \=.
4142 don't keep searching past point. */
4143 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4145 range = PT_BYTE - BEGV_BYTE - startpos;
4146 if (range < 0)
4147 return -1;
4149 #endif /* emacs */
4151 /* Update the fastmap now if not correct already. */
4152 if (fastmap && !bufp->fastmap_accurate)
4153 re_compile_fastmap (bufp);
4155 /* See whether the pattern is anchored. */
4156 anchored_start = (bufp->buffer[0] == begline);
4158 #ifdef emacs
4159 gl_state.object = re_match_object;
4161 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4163 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4165 #endif
4167 /* Loop through the string, looking for a place to start matching. */
4168 for (;;)
4170 /* If the pattern is anchored,
4171 skip quickly past places we cannot match.
4172 We don't bother to treat startpos == 0 specially
4173 because that case doesn't repeat. */
4174 if (anchored_start && startpos > 0)
4176 if (! ((startpos <= size1 ? string1[startpos - 1]
4177 : string2[startpos - size1 - 1])
4178 == '\n'))
4179 goto advance;
4182 /* If a fastmap is supplied, skip quickly over characters that
4183 cannot be the start of a match. If the pattern can match the
4184 null string, however, we don't need to skip characters; we want
4185 the first null string. */
4186 if (fastmap && startpos < total_size && !bufp->can_be_null)
4188 register re_char *d;
4189 register re_wchar_t buf_ch;
4191 d = POS_ADDR_VSTRING (startpos);
4193 if (range > 0) /* Searching forwards. */
4195 register int lim = 0;
4196 int irange = range;
4198 if (startpos < size1 && startpos + range >= size1)
4199 lim = range - (size1 - startpos);
4201 /* Written out as an if-else to avoid testing `translate'
4202 inside the loop. */
4203 if (RE_TRANSLATE_P (translate))
4205 if (multibyte)
4206 while (range > lim)
4208 int buf_charlen;
4210 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
4211 buf_charlen);
4213 buf_ch = RE_TRANSLATE (translate, buf_ch);
4214 if (buf_ch >= 0400
4215 || fastmap[buf_ch])
4216 break;
4218 range -= buf_charlen;
4219 d += buf_charlen;
4221 else
4222 while (range > lim
4223 && !fastmap[RE_TRANSLATE (translate, *d)])
4225 d++;
4226 range--;
4229 else
4230 while (range > lim && !fastmap[*d])
4232 d++;
4233 range--;
4236 startpos += irange - range;
4238 else /* Searching backwards. */
4240 int room = (startpos >= size1
4241 ? size2 + size1 - startpos
4242 : size1 - startpos);
4243 buf_ch = RE_STRING_CHAR (d, room);
4244 buf_ch = TRANSLATE (buf_ch);
4246 if (! (buf_ch >= 0400
4247 || fastmap[buf_ch]))
4248 goto advance;
4252 /* If can't match the null string, and that's all we have left, fail. */
4253 if (range >= 0 && startpos == total_size && fastmap
4254 && !bufp->can_be_null)
4255 return -1;
4257 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4258 startpos, regs, stop);
4259 #ifndef REGEX_MALLOC
4260 # ifdef C_ALLOCA
4261 alloca (0);
4262 # endif
4263 #endif
4265 if (val >= 0)
4266 return startpos;
4268 if (val == -2)
4269 return -2;
4271 advance:
4272 if (!range)
4273 break;
4274 else if (range > 0)
4276 /* Update STARTPOS to the next character boundary. */
4277 if (multibyte)
4279 re_char *p = POS_ADDR_VSTRING (startpos);
4280 re_char *pend = STOP_ADDR_VSTRING (startpos);
4281 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
4283 range -= len;
4284 if (range < 0)
4285 break;
4286 startpos += len;
4288 else
4290 range--;
4291 startpos++;
4294 else
4296 range++;
4297 startpos--;
4299 /* Update STARTPOS to the previous character boundary. */
4300 if (multibyte)
4302 re_char *p = POS_ADDR_VSTRING (startpos);
4303 int len = 0;
4305 /* Find the head of multibyte form. */
4306 while (!CHAR_HEAD_P (*p))
4307 p--, len++;
4309 /* Adjust it. */
4310 #if 0 /* XXX */
4311 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
4313 else
4314 #endif
4316 range += len;
4317 if (range > 0)
4318 break;
4320 startpos -= len;
4325 return -1;
4326 } /* re_search_2 */
4327 WEAK_ALIAS (__re_search_2, re_search_2)
4329 /* Declarations and macros for re_match_2. */
4331 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4332 register int len,
4333 RE_TRANSLATE_TYPE translate,
4334 const int multibyte));
4336 /* This converts PTR, a pointer into one of the search strings `string1'
4337 and `string2' into an offset from the beginning of that string. */
4338 #define POINTER_TO_OFFSET(ptr) \
4339 (FIRST_STRING_P (ptr) \
4340 ? ((regoff_t) ((ptr) - string1)) \
4341 : ((regoff_t) ((ptr) - string2 + size1)))
4343 /* Call before fetching a character with *d. This switches over to
4344 string2 if necessary.
4345 Check re_match_2_internal for a discussion of why end_match_2 might
4346 not be within string2 (but be equal to end_match_1 instead). */
4347 #define PREFETCH() \
4348 while (d == dend) \
4350 /* End of string2 => fail. */ \
4351 if (dend == end_match_2) \
4352 goto fail; \
4353 /* End of string1 => advance to string2. */ \
4354 d = string2; \
4355 dend = end_match_2; \
4358 /* Call before fetching a char with *d if you already checked other limits.
4359 This is meant for use in lookahead operations like wordend, etc..
4360 where we might need to look at parts of the string that might be
4361 outside of the LIMITs (i.e past `stop'). */
4362 #define PREFETCH_NOLIMIT() \
4363 if (d == end1) \
4365 d = string2; \
4366 dend = end_match_2; \
4369 /* Test if at very beginning or at very end of the virtual concatenation
4370 of `string1' and `string2'. If only one string, it's `string2'. */
4371 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4372 #define AT_STRINGS_END(d) ((d) == end2)
4375 /* Test if D points to a character which is word-constituent. We have
4376 two special cases to check for: if past the end of string1, look at
4377 the first character in string2; and if before the beginning of
4378 string2, look at the last character in string1. */
4379 #define WORDCHAR_P(d) \
4380 (SYNTAX ((d) == end1 ? *string2 \
4381 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4382 == Sword)
4384 /* Disabled due to a compiler bug -- see comment at case wordbound */
4386 /* The comment at case wordbound is following one, but we don't use
4387 AT_WORD_BOUNDARY anymore to support multibyte form.
4389 The DEC Alpha C compiler 3.x generates incorrect code for the
4390 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4391 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4392 macro and introducing temporary variables works around the bug. */
4394 #if 0
4395 /* Test if the character before D and the one at D differ with respect
4396 to being word-constituent. */
4397 #define AT_WORD_BOUNDARY(d) \
4398 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4399 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4400 #endif
4402 /* Free everything we malloc. */
4403 #ifdef MATCH_MAY_ALLOCATE
4404 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4405 # define FREE_VARIABLES() \
4406 do { \
4407 REGEX_FREE_STACK (fail_stack.stack); \
4408 FREE_VAR (regstart); \
4409 FREE_VAR (regend); \
4410 FREE_VAR (best_regstart); \
4411 FREE_VAR (best_regend); \
4412 } while (0)
4413 #else
4414 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4415 #endif /* not MATCH_MAY_ALLOCATE */
4418 /* Optimization routines. */
4420 /* If the operation is a match against one or more chars,
4421 return a pointer to the next operation, else return NULL. */
4422 static re_char *
4423 skip_one_char (p)
4424 re_char *p;
4426 switch (SWITCH_ENUM_CAST (*p++))
4428 case anychar:
4429 break;
4431 case exactn:
4432 p += *p + 1;
4433 break;
4435 case charset_not:
4436 case charset:
4437 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4439 int mcnt;
4440 p = CHARSET_RANGE_TABLE (p - 1);
4441 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4442 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4444 else
4445 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4446 break;
4448 case syntaxspec:
4449 case notsyntaxspec:
4450 #ifdef emacs
4451 case categoryspec:
4452 case notcategoryspec:
4453 #endif /* emacs */
4454 p++;
4455 break;
4457 default:
4458 p = NULL;
4460 return p;
4464 /* Jump over non-matching operations. */
4465 static unsigned char *
4466 skip_noops (p, pend)
4467 unsigned char *p, *pend;
4469 int mcnt;
4470 while (p < pend)
4472 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4474 case start_memory:
4475 case stop_memory:
4476 p += 2; break;
4477 case no_op:
4478 p += 1; break;
4479 case jump:
4480 p += 1;
4481 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4482 p += mcnt;
4483 break;
4484 default:
4485 return p;
4488 assert (p == pend);
4489 return p;
4492 /* Non-zero if "p1 matches something" implies "p2 fails". */
4493 static int
4494 mutually_exclusive_p (bufp, p1, p2)
4495 struct re_pattern_buffer *bufp;
4496 unsigned char *p1, *p2;
4498 re_opcode_t op2;
4499 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4500 unsigned char *pend = bufp->buffer + bufp->used;
4502 assert (p1 >= bufp->buffer && p1 < pend
4503 && p2 >= bufp->buffer && p2 <= pend);
4505 /* Skip over open/close-group commands.
4506 If what follows this loop is a ...+ construct,
4507 look at what begins its body, since we will have to
4508 match at least one of that. */
4509 p2 = skip_noops (p2, pend);
4510 /* The same skip can be done for p1, except that this function
4511 is only used in the case where p1 is a simple match operator. */
4512 /* p1 = skip_noops (p1, pend); */
4514 assert (p1 >= bufp->buffer && p1 < pend
4515 && p2 >= bufp->buffer && p2 <= pend);
4517 op2 = p2 == pend ? succeed : *p2;
4519 switch (SWITCH_ENUM_CAST (op2))
4521 case succeed:
4522 case endbuf:
4523 /* If we're at the end of the pattern, we can change. */
4524 if (skip_one_char (p1))
4526 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4527 return 1;
4529 break;
4531 case endline:
4532 case exactn:
4534 register re_wchar_t c
4535 = (re_opcode_t) *p2 == endline ? '\n'
4536 : RE_STRING_CHAR (p2 + 2, pend - p2 - 2);
4538 if ((re_opcode_t) *p1 == exactn)
4540 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4542 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4543 return 1;
4547 else if ((re_opcode_t) *p1 == charset
4548 || (re_opcode_t) *p1 == charset_not)
4550 int not = (re_opcode_t) *p1 == charset_not;
4552 /* Test if C is listed in charset (or charset_not)
4553 at `p1'. */
4554 if (SINGLE_BYTE_CHAR_P (c))
4556 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4557 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4558 not = !not;
4560 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4561 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4563 /* `not' is equal to 1 if c would match, which means
4564 that we can't change to pop_failure_jump. */
4565 if (!not)
4567 DEBUG_PRINT1 (" No match => fast loop.\n");
4568 return 1;
4571 else if ((re_opcode_t) *p1 == anychar
4572 && c == '\n')
4574 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4575 return 1;
4578 break;
4580 case charset:
4582 if ((re_opcode_t) *p1 == exactn)
4583 /* Reuse the code above. */
4584 return mutually_exclusive_p (bufp, p2, p1);
4586 /* It is hard to list up all the character in charset
4587 P2 if it includes multibyte character. Give up in
4588 such case. */
4589 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4591 /* Now, we are sure that P2 has no range table.
4592 So, for the size of bitmap in P2, `p2[1]' is
4593 enough. But P1 may have range table, so the
4594 size of bitmap table of P1 is extracted by
4595 using macro `CHARSET_BITMAP_SIZE'.
4597 Since we know that all the character listed in
4598 P2 is ASCII, it is enough to test only bitmap
4599 table of P1. */
4601 if ((re_opcode_t) *p1 == charset)
4603 int idx;
4604 /* We win if the charset inside the loop
4605 has no overlap with the one after the loop. */
4606 for (idx = 0;
4607 (idx < (int) p2[1]
4608 && idx < CHARSET_BITMAP_SIZE (p1));
4609 idx++)
4610 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4611 break;
4613 if (idx == p2[1]
4614 || idx == CHARSET_BITMAP_SIZE (p1))
4616 DEBUG_PRINT1 (" No match => fast loop.\n");
4617 return 1;
4620 else if ((re_opcode_t) *p1 == charset_not)
4622 int idx;
4623 /* We win if the charset_not inside the loop lists
4624 every character listed in the charset after. */
4625 for (idx = 0; idx < (int) p2[1]; idx++)
4626 if (! (p2[2 + idx] == 0
4627 || (idx < CHARSET_BITMAP_SIZE (p1)
4628 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4629 break;
4631 if (idx == p2[1])
4633 DEBUG_PRINT1 (" No match => fast loop.\n");
4634 return 1;
4639 break;
4641 case charset_not:
4642 switch (SWITCH_ENUM_CAST (*p1))
4644 case exactn:
4645 case charset:
4646 /* Reuse the code above. */
4647 return mutually_exclusive_p (bufp, p2, p1);
4648 case charset_not:
4649 /* When we have two charset_not, it's very unlikely that
4650 they don't overlap. The union of the two sets of excluded
4651 chars should cover all possible chars, which, as a matter of
4652 fact, is virtually impossible in multibyte buffers. */
4653 break;
4655 break;
4657 case wordend:
4658 case notsyntaxspec:
4659 return ((re_opcode_t) *p1 == syntaxspec
4660 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4662 case wordbeg:
4663 case syntaxspec:
4664 return ((re_opcode_t) *p1 == notsyntaxspec
4665 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4667 case wordbound:
4668 return (((re_opcode_t) *p1 == notsyntaxspec
4669 || (re_opcode_t) *p1 == syntaxspec)
4670 && p1[1] == Sword);
4672 #ifdef emacs
4673 case categoryspec:
4674 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4675 case notcategoryspec:
4676 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4677 #endif /* emacs */
4679 default:
4683 /* Safe default. */
4684 return 0;
4688 /* Matching routines. */
4690 #ifndef emacs /* Emacs never uses this. */
4691 /* re_match is like re_match_2 except it takes only a single string. */
4694 re_match (bufp, string, size, pos, regs)
4695 struct re_pattern_buffer *bufp;
4696 const char *string;
4697 int size, pos;
4698 struct re_registers *regs;
4700 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4701 pos, regs, size);
4702 # if defined C_ALLOCA && !defined REGEX_MALLOC
4703 alloca (0);
4704 # endif
4705 return result;
4707 WEAK_ALIAS (__re_match, re_match)
4708 #endif /* not emacs */
4710 #ifdef emacs
4711 /* In Emacs, this is the string or buffer in which we
4712 are matching. It is used for looking up syntax properties. */
4713 Lisp_Object re_match_object;
4714 #endif
4716 /* re_match_2 matches the compiled pattern in BUFP against the
4717 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4718 and SIZE2, respectively). We start matching at POS, and stop
4719 matching at STOP.
4721 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4722 store offsets for the substring each group matched in REGS. See the
4723 documentation for exactly how many groups we fill.
4725 We return -1 if no match, -2 if an internal error (such as the
4726 failure stack overflowing). Otherwise, we return the length of the
4727 matched substring. */
4730 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4731 struct re_pattern_buffer *bufp;
4732 const char *string1, *string2;
4733 int size1, size2;
4734 int pos;
4735 struct re_registers *regs;
4736 int stop;
4738 int result;
4740 #ifdef emacs
4741 int charpos;
4742 gl_state.object = re_match_object;
4743 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4744 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4745 #endif
4747 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4748 (re_char*) string2, size2,
4749 pos, regs, stop);
4750 #if defined C_ALLOCA && !defined REGEX_MALLOC
4751 alloca (0);
4752 #endif
4753 return result;
4755 WEAK_ALIAS (__re_match_2, re_match_2)
4757 /* This is a separate function so that we can force an alloca cleanup
4758 afterwards. */
4759 static int
4760 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4761 struct re_pattern_buffer *bufp;
4762 re_char *string1, *string2;
4763 int size1, size2;
4764 int pos;
4765 struct re_registers *regs;
4766 int stop;
4768 /* General temporaries. */
4769 int mcnt;
4770 size_t reg;
4771 boolean not;
4773 /* Just past the end of the corresponding string. */
4774 re_char *end1, *end2;
4776 /* Pointers into string1 and string2, just past the last characters in
4777 each to consider matching. */
4778 re_char *end_match_1, *end_match_2;
4780 /* Where we are in the data, and the end of the current string. */
4781 re_char *d, *dend;
4783 /* Used sometimes to remember where we were before starting matching
4784 an operator so that we can go back in case of failure. This "atomic"
4785 behavior of matching opcodes is indispensable to the correctness
4786 of the on_failure_keep_string_jump optimization. */
4787 re_char *dfail;
4789 /* Where we are in the pattern, and the end of the pattern. */
4790 re_char *p = bufp->buffer;
4791 re_char *pend = p + bufp->used;
4793 /* We use this to map every character in the string. */
4794 RE_TRANSLATE_TYPE translate = bufp->translate;
4796 /* Nonzero if we have to concern multibyte character. */
4797 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4799 /* Failure point stack. Each place that can handle a failure further
4800 down the line pushes a failure point on this stack. It consists of
4801 regstart, and regend for all registers corresponding to
4802 the subexpressions we're currently inside, plus the number of such
4803 registers, and, finally, two char *'s. The first char * is where
4804 to resume scanning the pattern; the second one is where to resume
4805 scanning the strings. */
4806 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4807 fail_stack_type fail_stack;
4808 #endif
4809 #ifdef DEBUG
4810 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4811 #endif
4813 #if defined REL_ALLOC && defined REGEX_MALLOC
4814 /* This holds the pointer to the failure stack, when
4815 it is allocated relocatably. */
4816 fail_stack_elt_t *failure_stack_ptr;
4817 #endif
4819 /* We fill all the registers internally, independent of what we
4820 return, for use in backreferences. The number here includes
4821 an element for register zero. */
4822 size_t num_regs = bufp->re_nsub + 1;
4824 /* Information on the contents of registers. These are pointers into
4825 the input strings; they record just what was matched (on this
4826 attempt) by a subexpression part of the pattern, that is, the
4827 regnum-th regstart pointer points to where in the pattern we began
4828 matching and the regnum-th regend points to right after where we
4829 stopped matching the regnum-th subexpression. (The zeroth register
4830 keeps track of what the whole pattern matches.) */
4831 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4832 re_char **regstart, **regend;
4833 #endif
4835 /* The following record the register info as found in the above
4836 variables when we find a match better than any we've seen before.
4837 This happens as we backtrack through the failure points, which in
4838 turn happens only if we have not yet matched the entire string. */
4839 unsigned best_regs_set = false;
4840 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4841 re_char **best_regstart, **best_regend;
4842 #endif
4844 /* Logically, this is `best_regend[0]'. But we don't want to have to
4845 allocate space for that if we're not allocating space for anything
4846 else (see below). Also, we never need info about register 0 for
4847 any of the other register vectors, and it seems rather a kludge to
4848 treat `best_regend' differently than the rest. So we keep track of
4849 the end of the best match so far in a separate variable. We
4850 initialize this to NULL so that when we backtrack the first time
4851 and need to test it, it's not garbage. */
4852 re_char *match_end = NULL;
4854 #ifdef DEBUG
4855 /* Counts the total number of registers pushed. */
4856 unsigned num_regs_pushed = 0;
4857 #endif
4859 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4861 INIT_FAIL_STACK ();
4863 #ifdef MATCH_MAY_ALLOCATE
4864 /* Do not bother to initialize all the register variables if there are
4865 no groups in the pattern, as it takes a fair amount of time. If
4866 there are groups, we include space for register 0 (the whole
4867 pattern), even though we never use it, since it simplifies the
4868 array indexing. We should fix this. */
4869 if (bufp->re_nsub)
4871 regstart = REGEX_TALLOC (num_regs, re_char *);
4872 regend = REGEX_TALLOC (num_regs, re_char *);
4873 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4874 best_regend = REGEX_TALLOC (num_regs, re_char *);
4876 if (!(regstart && regend && best_regstart && best_regend))
4878 FREE_VARIABLES ();
4879 return -2;
4882 else
4884 /* We must initialize all our variables to NULL, so that
4885 `FREE_VARIABLES' doesn't try to free them. */
4886 regstart = regend = best_regstart = best_regend = NULL;
4888 #endif /* MATCH_MAY_ALLOCATE */
4890 /* The starting position is bogus. */
4891 if (pos < 0 || pos > size1 + size2)
4893 FREE_VARIABLES ();
4894 return -1;
4897 /* Initialize subexpression text positions to -1 to mark ones that no
4898 start_memory/stop_memory has been seen for. Also initialize the
4899 register information struct. */
4900 for (reg = 1; reg < num_regs; reg++)
4901 regstart[reg] = regend[reg] = NULL;
4903 /* We move `string1' into `string2' if the latter's empty -- but not if
4904 `string1' is null. */
4905 if (size2 == 0 && string1 != NULL)
4907 string2 = string1;
4908 size2 = size1;
4909 string1 = 0;
4910 size1 = 0;
4912 end1 = string1 + size1;
4913 end2 = string2 + size2;
4915 /* `p' scans through the pattern as `d' scans through the data.
4916 `dend' is the end of the input string that `d' points within. `d'
4917 is advanced into the following input string whenever necessary, but
4918 this happens before fetching; therefore, at the beginning of the
4919 loop, `d' can be pointing at the end of a string, but it cannot
4920 equal `string2'. */
4921 if (pos >= size1)
4923 /* Only match within string2. */
4924 d = string2 + pos - size1;
4925 dend = end_match_2 = string2 + stop - size1;
4926 end_match_1 = end1; /* Just to give it a value. */
4928 else
4930 if (stop < size1)
4932 /* Only match within string1. */
4933 end_match_1 = string1 + stop;
4934 /* BEWARE!
4935 When we reach end_match_1, PREFETCH normally switches to string2.
4936 But in the present case, this means that just doing a PREFETCH
4937 makes us jump from `stop' to `gap' within the string.
4938 What we really want here is for the search to stop as
4939 soon as we hit end_match_1. That's why we set end_match_2
4940 to end_match_1 (since PREFETCH fails as soon as we hit
4941 end_match_2). */
4942 end_match_2 = end_match_1;
4944 else
4945 { /* It's important to use this code when stop == size so that
4946 moving `d' from end1 to string2 will not prevent the d == dend
4947 check from catching the end of string. */
4948 end_match_1 = end1;
4949 end_match_2 = string2 + stop - size1;
4951 d = string1 + pos;
4952 dend = end_match_1;
4955 DEBUG_PRINT1 ("The compiled pattern is: ");
4956 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4957 DEBUG_PRINT1 ("The string to match is: `");
4958 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4959 DEBUG_PRINT1 ("'\n");
4961 /* This loops over pattern commands. It exits by returning from the
4962 function if the match is complete, or it drops through if the match
4963 fails at this starting point in the input data. */
4964 for (;;)
4966 DEBUG_PRINT2 ("\n%p: ", p);
4968 if (p == pend)
4969 { /* End of pattern means we might have succeeded. */
4970 DEBUG_PRINT1 ("end of pattern ... ");
4972 /* If we haven't matched the entire string, and we want the
4973 longest match, try backtracking. */
4974 if (d != end_match_2)
4976 /* 1 if this match ends in the same string (string1 or string2)
4977 as the best previous match. */
4978 boolean same_str_p = (FIRST_STRING_P (match_end)
4979 == FIRST_STRING_P (d));
4980 /* 1 if this match is the best seen so far. */
4981 boolean best_match_p;
4983 /* AIX compiler got confused when this was combined
4984 with the previous declaration. */
4985 if (same_str_p)
4986 best_match_p = d > match_end;
4987 else
4988 best_match_p = !FIRST_STRING_P (d);
4990 DEBUG_PRINT1 ("backtracking.\n");
4992 if (!FAIL_STACK_EMPTY ())
4993 { /* More failure points to try. */
4995 /* If exceeds best match so far, save it. */
4996 if (!best_regs_set || best_match_p)
4998 best_regs_set = true;
4999 match_end = d;
5001 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5003 for (reg = 1; reg < num_regs; reg++)
5005 best_regstart[reg] = regstart[reg];
5006 best_regend[reg] = regend[reg];
5009 goto fail;
5012 /* If no failure points, don't restore garbage. And if
5013 last match is real best match, don't restore second
5014 best one. */
5015 else if (best_regs_set && !best_match_p)
5017 restore_best_regs:
5018 /* Restore best match. It may happen that `dend ==
5019 end_match_1' while the restored d is in string2.
5020 For example, the pattern `x.*y.*z' against the
5021 strings `x-' and `y-z-', if the two strings are
5022 not consecutive in memory. */
5023 DEBUG_PRINT1 ("Restoring best registers.\n");
5025 d = match_end;
5026 dend = ((d >= string1 && d <= end1)
5027 ? end_match_1 : end_match_2);
5029 for (reg = 1; reg < num_regs; reg++)
5031 regstart[reg] = best_regstart[reg];
5032 regend[reg] = best_regend[reg];
5035 } /* d != end_match_2 */
5037 succeed_label:
5038 DEBUG_PRINT1 ("Accepting match.\n");
5040 /* If caller wants register contents data back, do it. */
5041 if (regs && !bufp->no_sub)
5043 /* Have the register data arrays been allocated? */
5044 if (bufp->regs_allocated == REGS_UNALLOCATED)
5045 { /* No. So allocate them with malloc. We need one
5046 extra element beyond `num_regs' for the `-1' marker
5047 GNU code uses. */
5048 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5049 regs->start = TALLOC (regs->num_regs, regoff_t);
5050 regs->end = TALLOC (regs->num_regs, regoff_t);
5051 if (regs->start == NULL || regs->end == NULL)
5053 FREE_VARIABLES ();
5054 return -2;
5056 bufp->regs_allocated = REGS_REALLOCATE;
5058 else if (bufp->regs_allocated == REGS_REALLOCATE)
5059 { /* Yes. If we need more elements than were already
5060 allocated, reallocate them. If we need fewer, just
5061 leave it alone. */
5062 if (regs->num_regs < num_regs + 1)
5064 regs->num_regs = num_regs + 1;
5065 RETALLOC (regs->start, regs->num_regs, regoff_t);
5066 RETALLOC (regs->end, regs->num_regs, regoff_t);
5067 if (regs->start == NULL || regs->end == NULL)
5069 FREE_VARIABLES ();
5070 return -2;
5074 else
5076 /* These braces fend off a "empty body in an else-statement"
5077 warning under GCC when assert expands to nothing. */
5078 assert (bufp->regs_allocated == REGS_FIXED);
5081 /* Convert the pointer data in `regstart' and `regend' to
5082 indices. Register zero has to be set differently,
5083 since we haven't kept track of any info for it. */
5084 if (regs->num_regs > 0)
5086 regs->start[0] = pos;
5087 regs->end[0] = POINTER_TO_OFFSET (d);
5090 /* Go through the first `min (num_regs, regs->num_regs)'
5091 registers, since that is all we initialized. */
5092 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5094 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5095 regs->start[reg] = regs->end[reg] = -1;
5096 else
5098 regs->start[reg]
5099 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5100 regs->end[reg]
5101 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5105 /* If the regs structure we return has more elements than
5106 were in the pattern, set the extra elements to -1. If
5107 we (re)allocated the registers, this is the case,
5108 because we always allocate enough to have at least one
5109 -1 at the end. */
5110 for (reg = num_regs; reg < regs->num_regs; reg++)
5111 regs->start[reg] = regs->end[reg] = -1;
5112 } /* regs && !bufp->no_sub */
5114 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5115 nfailure_points_pushed, nfailure_points_popped,
5116 nfailure_points_pushed - nfailure_points_popped);
5117 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5119 mcnt = POINTER_TO_OFFSET (d) - pos;
5121 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5123 FREE_VARIABLES ();
5124 return mcnt;
5127 /* Otherwise match next pattern command. */
5128 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5130 /* Ignore these. Used to ignore the n of succeed_n's which
5131 currently have n == 0. */
5132 case no_op:
5133 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5134 break;
5136 case succeed:
5137 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5138 goto succeed_label;
5140 /* Match the next n pattern characters exactly. The following
5141 byte in the pattern defines n, and the n bytes after that
5142 are the characters to match. */
5143 case exactn:
5144 mcnt = *p++;
5145 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5147 /* Remember the start point to rollback upon failure. */
5148 dfail = d;
5150 /* This is written out as an if-else so we don't waste time
5151 testing `translate' inside the loop. */
5152 if (RE_TRANSLATE_P (translate))
5154 if (multibyte)
5157 int pat_charlen, buf_charlen;
5158 unsigned int pat_ch, buf_ch;
5160 PREFETCH ();
5161 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
5162 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
5164 if (RE_TRANSLATE (translate, buf_ch)
5165 != pat_ch)
5167 d = dfail;
5168 goto fail;
5171 p += pat_charlen;
5172 d += buf_charlen;
5173 mcnt -= pat_charlen;
5175 while (mcnt > 0);
5176 else
5179 PREFETCH ();
5180 if (RE_TRANSLATE (translate, *d) != *p++)
5182 d = dfail;
5183 goto fail;
5185 d++;
5187 while (--mcnt);
5189 else
5193 PREFETCH ();
5194 if (*d++ != *p++)
5196 d = dfail;
5197 goto fail;
5200 while (--mcnt);
5202 break;
5205 /* Match any character except possibly a newline or a null. */
5206 case anychar:
5208 int buf_charlen;
5209 re_wchar_t buf_ch;
5211 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5213 PREFETCH ();
5214 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
5215 buf_ch = TRANSLATE (buf_ch);
5217 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5218 && buf_ch == '\n')
5219 || ((bufp->syntax & RE_DOT_NOT_NULL)
5220 && buf_ch == '\000'))
5221 goto fail;
5223 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5224 d += buf_charlen;
5226 break;
5229 case charset:
5230 case charset_not:
5232 register unsigned int c;
5233 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5234 int len;
5236 /* Start of actual range_table, or end of bitmap if there is no
5237 range table. */
5238 re_char *range_table;
5240 /* Nonzero if there is a range table. */
5241 int range_table_exists;
5243 /* Number of ranges of range table. This is not included
5244 in the initial byte-length of the command. */
5245 int count = 0;
5247 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5249 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5251 if (range_table_exists)
5253 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5254 EXTRACT_NUMBER_AND_INCR (count, range_table);
5257 PREFETCH ();
5258 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5259 c = TRANSLATE (c); /* The character to match. */
5261 if (SINGLE_BYTE_CHAR_P (c))
5262 { /* Lookup bitmap. */
5263 /* Cast to `unsigned' instead of `unsigned char' in
5264 case the bit list is a full 32 bytes long. */
5265 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5266 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5267 not = !not;
5269 #ifdef emacs
5270 else if (range_table_exists)
5272 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5274 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5275 | (class_bits & BIT_MULTIBYTE)
5276 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5277 | (class_bits & BIT_SPACE && ISSPACE (c))
5278 | (class_bits & BIT_UPPER && ISUPPER (c))
5279 | (class_bits & BIT_WORD && ISWORD (c)))
5280 not = !not;
5281 else
5282 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5284 #endif /* emacs */
5286 if (range_table_exists)
5287 p = CHARSET_RANGE_TABLE_END (range_table, count);
5288 else
5289 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5291 if (!not) goto fail;
5293 d += len;
5294 break;
5298 /* The beginning of a group is represented by start_memory.
5299 The argument is the register number. The text
5300 matched within the group is recorded (in the internal
5301 registers data structure) under the register number. */
5302 case start_memory:
5303 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5305 /* In case we need to undo this operation (via backtracking). */
5306 PUSH_FAILURE_REG ((unsigned int)*p);
5308 regstart[*p] = d;
5309 regend[*p] = NULL; /* probably unnecessary. -sm */
5310 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5312 /* Move past the register number and inner group count. */
5313 p += 1;
5314 break;
5317 /* The stop_memory opcode represents the end of a group. Its
5318 argument is the same as start_memory's: the register number. */
5319 case stop_memory:
5320 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5322 assert (!REG_UNSET (regstart[*p]));
5323 /* Strictly speaking, there should be code such as:
5325 assert (REG_UNSET (regend[*p]));
5326 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5328 But the only info to be pushed is regend[*p] and it is known to
5329 be UNSET, so there really isn't anything to push.
5330 Not pushing anything, on the other hand deprives us from the
5331 guarantee that regend[*p] is UNSET since undoing this operation
5332 will not reset its value properly. This is not important since
5333 the value will only be read on the next start_memory or at
5334 the very end and both events can only happen if this stop_memory
5335 is *not* undone. */
5337 regend[*p] = d;
5338 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5340 /* Move past the register number and the inner group count. */
5341 p += 1;
5342 break;
5345 /* \<digit> has been turned into a `duplicate' command which is
5346 followed by the numeric value of <digit> as the register number. */
5347 case duplicate:
5349 register re_char *d2, *dend2;
5350 int regno = *p++; /* Get which register to match against. */
5351 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5353 /* Can't back reference a group which we've never matched. */
5354 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5355 goto fail;
5357 /* Where in input to try to start matching. */
5358 d2 = regstart[regno];
5360 /* Remember the start point to rollback upon failure. */
5361 dfail = d;
5363 /* Where to stop matching; if both the place to start and
5364 the place to stop matching are in the same string, then
5365 set to the place to stop, otherwise, for now have to use
5366 the end of the first string. */
5368 dend2 = ((FIRST_STRING_P (regstart[regno])
5369 == FIRST_STRING_P (regend[regno]))
5370 ? regend[regno] : end_match_1);
5371 for (;;)
5373 /* If necessary, advance to next segment in register
5374 contents. */
5375 while (d2 == dend2)
5377 if (dend2 == end_match_2) break;
5378 if (dend2 == regend[regno]) break;
5380 /* End of string1 => advance to string2. */
5381 d2 = string2;
5382 dend2 = regend[regno];
5384 /* At end of register contents => success */
5385 if (d2 == dend2) break;
5387 /* If necessary, advance to next segment in data. */
5388 PREFETCH ();
5390 /* How many characters left in this segment to match. */
5391 mcnt = dend - d;
5393 /* Want how many consecutive characters we can match in
5394 one shot, so, if necessary, adjust the count. */
5395 if (mcnt > dend2 - d2)
5396 mcnt = dend2 - d2;
5398 /* Compare that many; failure if mismatch, else move
5399 past them. */
5400 if (RE_TRANSLATE_P (translate)
5401 ? bcmp_translate (d, d2, mcnt, translate, multibyte)
5402 : memcmp (d, d2, mcnt))
5404 d = dfail;
5405 goto fail;
5407 d += mcnt, d2 += mcnt;
5410 break;
5413 /* begline matches the empty string at the beginning of the string
5414 (unless `not_bol' is set in `bufp'), and after newlines. */
5415 case begline:
5416 DEBUG_PRINT1 ("EXECUTING begline.\n");
5418 if (AT_STRINGS_BEG (d))
5420 if (!bufp->not_bol) break;
5422 else
5424 unsigned char c;
5425 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5426 if (c == '\n')
5427 break;
5429 /* In all other cases, we fail. */
5430 goto fail;
5433 /* endline is the dual of begline. */
5434 case endline:
5435 DEBUG_PRINT1 ("EXECUTING endline.\n");
5437 if (AT_STRINGS_END (d))
5439 if (!bufp->not_eol) break;
5441 else
5443 PREFETCH_NOLIMIT ();
5444 if (*d == '\n')
5445 break;
5447 goto fail;
5450 /* Match at the very beginning of the data. */
5451 case begbuf:
5452 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5453 if (AT_STRINGS_BEG (d))
5454 break;
5455 goto fail;
5458 /* Match at the very end of the data. */
5459 case endbuf:
5460 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5461 if (AT_STRINGS_END (d))
5462 break;
5463 goto fail;
5466 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5467 pushes NULL as the value for the string on the stack. Then
5468 `POP_FAILURE_POINT' will keep the current value for the
5469 string, instead of restoring it. To see why, consider
5470 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5471 then the . fails against the \n. But the next thing we want
5472 to do is match the \n against the \n; if we restored the
5473 string value, we would be back at the foo.
5475 Because this is used only in specific cases, we don't need to
5476 check all the things that `on_failure_jump' does, to make
5477 sure the right things get saved on the stack. Hence we don't
5478 share its code. The only reason to push anything on the
5479 stack at all is that otherwise we would have to change
5480 `anychar's code to do something besides goto fail in this
5481 case; that seems worse than this. */
5482 case on_failure_keep_string_jump:
5483 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5484 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5485 mcnt, p + mcnt);
5487 PUSH_FAILURE_POINT (p - 3, NULL);
5488 break;
5490 /* A nasty loop is introduced by the non-greedy *? and +?.
5491 With such loops, the stack only ever contains one failure point
5492 at a time, so that a plain on_failure_jump_loop kind of
5493 cycle detection cannot work. Worse yet, such a detection
5494 can not only fail to detect a cycle, but it can also wrongly
5495 detect a cycle (between different instantiations of the same
5496 loop).
5497 So the method used for those nasty loops is a little different:
5498 We use a special cycle-detection-stack-frame which is pushed
5499 when the on_failure_jump_nastyloop failure-point is *popped*.
5500 This special frame thus marks the beginning of one iteration
5501 through the loop and we can hence easily check right here
5502 whether something matched between the beginning and the end of
5503 the loop. */
5504 case on_failure_jump_nastyloop:
5505 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5506 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5507 mcnt, p + mcnt);
5509 assert ((re_opcode_t)p[-4] == no_op);
5511 int cycle = 0;
5512 CHECK_INFINITE_LOOP (p - 4, d);
5513 if (!cycle)
5514 /* If there's a cycle, just continue without pushing
5515 this failure point. The failure point is the "try again"
5516 option, which shouldn't be tried.
5517 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5518 PUSH_FAILURE_POINT (p - 3, d);
5520 break;
5522 /* Simple loop detecting on_failure_jump: just check on the
5523 failure stack if the same spot was already hit earlier. */
5524 case on_failure_jump_loop:
5525 on_failure:
5526 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5527 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5528 mcnt, p + mcnt);
5530 int cycle = 0;
5531 CHECK_INFINITE_LOOP (p - 3, d);
5532 if (cycle)
5533 /* If there's a cycle, get out of the loop, as if the matching
5534 had failed. We used to just `goto fail' here, but that was
5535 aborting the search a bit too early: we want to keep the
5536 empty-loop-match and keep matching after the loop.
5537 We want (x?)*y\1z to match both xxyz and xxyxz. */
5538 p += mcnt;
5539 else
5540 PUSH_FAILURE_POINT (p - 3, d);
5542 break;
5545 /* Uses of on_failure_jump:
5547 Each alternative starts with an on_failure_jump that points
5548 to the beginning of the next alternative. Each alternative
5549 except the last ends with a jump that in effect jumps past
5550 the rest of the alternatives. (They really jump to the
5551 ending jump of the following alternative, because tensioning
5552 these jumps is a hassle.)
5554 Repeats start with an on_failure_jump that points past both
5555 the repetition text and either the following jump or
5556 pop_failure_jump back to this on_failure_jump. */
5557 case on_failure_jump:
5558 IMMEDIATE_QUIT_CHECK;
5559 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5560 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5561 mcnt, p + mcnt);
5563 PUSH_FAILURE_POINT (p -3, d);
5564 break;
5566 /* This operation is used for greedy *.
5567 Compare the beginning of the repeat with what in the
5568 pattern follows its end. If we can establish that there
5569 is nothing that they would both match, i.e., that we
5570 would have to backtrack because of (as in, e.g., `a*a')
5571 then we can use a non-backtracking loop based on
5572 on_failure_keep_string_jump instead of on_failure_jump. */
5573 case on_failure_jump_smart:
5574 IMMEDIATE_QUIT_CHECK;
5575 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5576 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5577 mcnt, p + mcnt);
5579 re_char *p1 = p; /* Next operation. */
5580 /* Here, we discard `const', making re_match non-reentrant. */
5581 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5582 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5584 p -= 3; /* Reset so that we will re-execute the
5585 instruction once it's been changed. */
5587 EXTRACT_NUMBER (mcnt, p2 - 2);
5589 /* Ensure this is a indeed the trivial kind of loop
5590 we are expecting. */
5591 assert (skip_one_char (p1) == p2 - 3);
5592 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5593 DEBUG_STATEMENT (debug += 2);
5594 if (mutually_exclusive_p (bufp, p1, p2))
5596 /* Use a fast `on_failure_keep_string_jump' loop. */
5597 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5598 *p3 = (unsigned char) on_failure_keep_string_jump;
5599 STORE_NUMBER (p2 - 2, mcnt + 3);
5601 else
5603 /* Default to a safe `on_failure_jump' loop. */
5604 DEBUG_PRINT1 (" smart default => slow loop.\n");
5605 *p3 = (unsigned char) on_failure_jump;
5607 DEBUG_STATEMENT (debug -= 2);
5609 break;
5611 /* Unconditionally jump (without popping any failure points). */
5612 case jump:
5613 unconditional_jump:
5614 IMMEDIATE_QUIT_CHECK;
5615 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5616 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5617 p += mcnt; /* Do the jump. */
5618 DEBUG_PRINT2 ("(to %p).\n", p);
5619 break;
5622 /* Have to succeed matching what follows at least n times.
5623 After that, handle like `on_failure_jump'. */
5624 case succeed_n:
5625 /* Signedness doesn't matter since we only compare MCNT to 0. */
5626 EXTRACT_NUMBER (mcnt, p + 2);
5627 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5629 /* Originally, mcnt is how many times we HAVE to succeed. */
5630 if (mcnt != 0)
5632 /* Here, we discard `const', making re_match non-reentrant. */
5633 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5634 mcnt--;
5635 p += 4;
5636 PUSH_NUMBER (p2, mcnt);
5638 else
5639 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5640 goto on_failure;
5641 break;
5643 case jump_n:
5644 /* Signedness doesn't matter since we only compare MCNT to 0. */
5645 EXTRACT_NUMBER (mcnt, p + 2);
5646 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5648 /* Originally, this is how many times we CAN jump. */
5649 if (mcnt != 0)
5651 /* Here, we discard `const', making re_match non-reentrant. */
5652 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5653 mcnt--;
5654 PUSH_NUMBER (p2, mcnt);
5655 goto unconditional_jump;
5657 /* If don't have to jump any more, skip over the rest of command. */
5658 else
5659 p += 4;
5660 break;
5662 case set_number_at:
5664 unsigned char *p2; /* Location of the counter. */
5665 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5667 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5668 /* Here, we discard `const', making re_match non-reentrant. */
5669 p2 = (unsigned char*) p + mcnt;
5670 /* Signedness doesn't matter since we only copy MCNT's bits . */
5671 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5672 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5673 PUSH_NUMBER (p2, mcnt);
5674 break;
5677 case wordbound:
5678 case notwordbound:
5679 not = (re_opcode_t) *(p - 1) == notwordbound;
5680 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5682 /* We SUCCEED (or FAIL) in one of the following cases: */
5684 /* Case 1: D is at the beginning or the end of string. */
5685 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5686 not = !not;
5687 else
5689 /* C1 is the character before D, S1 is the syntax of C1, C2
5690 is the character at D, and S2 is the syntax of C2. */
5691 re_wchar_t c1, c2;
5692 int s1, s2;
5693 #ifdef emacs
5694 int offset = PTR_TO_OFFSET (d - 1);
5695 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5696 UPDATE_SYNTAX_TABLE (charpos);
5697 #endif
5698 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5699 s1 = SYNTAX (c1);
5700 #ifdef emacs
5701 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5702 #endif
5703 PREFETCH_NOLIMIT ();
5704 c2 = RE_STRING_CHAR (d, dend - d);
5705 s2 = SYNTAX (c2);
5707 if (/* Case 2: Only one of S1 and S2 is Sword. */
5708 ((s1 == Sword) != (s2 == Sword))
5709 /* Case 3: Both of S1 and S2 are Sword, and macro
5710 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5711 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5712 not = !not;
5714 if (not)
5715 break;
5716 else
5717 goto fail;
5719 case wordbeg:
5720 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5722 /* We FAIL in one of the following cases: */
5724 /* Case 1: D is at the end of string. */
5725 if (AT_STRINGS_END (d))
5726 goto fail;
5727 else
5729 /* C1 is the character before D, S1 is the syntax of C1, C2
5730 is the character at D, and S2 is the syntax of C2. */
5731 re_wchar_t c1, c2;
5732 int s1, s2;
5733 #ifdef emacs
5734 int offset = PTR_TO_OFFSET (d);
5735 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5736 UPDATE_SYNTAX_TABLE (charpos);
5737 #endif
5738 PREFETCH ();
5739 c2 = RE_STRING_CHAR (d, dend - d);
5740 s2 = SYNTAX (c2);
5742 /* Case 2: S2 is not Sword. */
5743 if (s2 != Sword)
5744 goto fail;
5746 /* Case 3: D is not at the beginning of string ... */
5747 if (!AT_STRINGS_BEG (d))
5749 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5750 #ifdef emacs
5751 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5752 #endif
5753 s1 = SYNTAX (c1);
5755 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5756 returns 0. */
5757 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5758 goto fail;
5761 break;
5763 case wordend:
5764 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5766 /* We FAIL in one of the following cases: */
5768 /* Case 1: D is at the beginning of string. */
5769 if (AT_STRINGS_BEG (d))
5770 goto fail;
5771 else
5773 /* C1 is the character before D, S1 is the syntax of C1, C2
5774 is the character at D, and S2 is the syntax of C2. */
5775 re_wchar_t c1, c2;
5776 int s1, s2;
5777 #ifdef emacs
5778 int offset = PTR_TO_OFFSET (d) - 1;
5779 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5780 UPDATE_SYNTAX_TABLE (charpos);
5781 #endif
5782 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5783 s1 = SYNTAX (c1);
5785 /* Case 2: S1 is not Sword. */
5786 if (s1 != Sword)
5787 goto fail;
5789 /* Case 3: D is not at the end of string ... */
5790 if (!AT_STRINGS_END (d))
5792 PREFETCH_NOLIMIT ();
5793 c2 = RE_STRING_CHAR (d, dend - d);
5794 #ifdef emacs
5795 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5796 #endif
5797 s2 = SYNTAX (c2);
5799 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5800 returns 0. */
5801 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5802 goto fail;
5805 break;
5807 case syntaxspec:
5808 case notsyntaxspec:
5809 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
5810 mcnt = *p++;
5811 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
5812 PREFETCH ();
5813 #ifdef emacs
5815 int offset = PTR_TO_OFFSET (d);
5816 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5817 UPDATE_SYNTAX_TABLE (pos1);
5819 #endif
5821 int len;
5822 re_wchar_t c;
5824 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5826 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
5827 goto fail;
5828 d += len;
5830 break;
5832 #ifdef emacs
5833 case before_dot:
5834 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5835 if (PTR_BYTE_POS (d) >= PT_BYTE)
5836 goto fail;
5837 break;
5839 case at_dot:
5840 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5841 if (PTR_BYTE_POS (d) != PT_BYTE)
5842 goto fail;
5843 break;
5845 case after_dot:
5846 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5847 if (PTR_BYTE_POS (d) <= PT_BYTE)
5848 goto fail;
5849 break;
5851 case categoryspec:
5852 case notcategoryspec:
5853 not = (re_opcode_t) *(p - 1) == notcategoryspec;
5854 mcnt = *p++;
5855 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
5856 PREFETCH ();
5858 int len;
5859 re_wchar_t c;
5861 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5863 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
5864 goto fail;
5865 d += len;
5867 break;
5869 #endif /* emacs */
5871 default:
5872 abort ();
5874 continue; /* Successfully executed one pattern command; keep going. */
5877 /* We goto here if a matching operation fails. */
5878 fail:
5879 IMMEDIATE_QUIT_CHECK;
5880 if (!FAIL_STACK_EMPTY ())
5882 re_char *str, *pat;
5883 /* A restart point is known. Restore to that state. */
5884 DEBUG_PRINT1 ("\nFAIL:\n");
5885 POP_FAILURE_POINT (str, pat);
5886 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5888 case on_failure_keep_string_jump:
5889 assert (str == NULL);
5890 goto continue_failure_jump;
5892 case on_failure_jump_nastyloop:
5893 assert ((re_opcode_t)pat[-2] == no_op);
5894 PUSH_FAILURE_POINT (pat - 2, str);
5895 /* Fallthrough */
5897 case on_failure_jump_loop:
5898 case on_failure_jump:
5899 case succeed_n:
5900 d = str;
5901 continue_failure_jump:
5902 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5903 p = pat + mcnt;
5904 break;
5906 case no_op:
5907 /* A special frame used for nastyloops. */
5908 goto fail;
5910 default:
5911 abort();
5914 assert (p >= bufp->buffer && p <= pend);
5916 if (d >= string1 && d <= end1)
5917 dend = end_match_1;
5919 else
5920 break; /* Matching at this starting point really fails. */
5921 } /* for (;;) */
5923 if (best_regs_set)
5924 goto restore_best_regs;
5926 FREE_VARIABLES ();
5928 return -1; /* Failure to match. */
5929 } /* re_match_2 */
5931 /* Subroutine definitions for re_match_2. */
5933 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5934 bytes; nonzero otherwise. */
5936 static int
5937 bcmp_translate (s1, s2, len, translate, multibyte)
5938 re_char *s1, *s2;
5939 register int len;
5940 RE_TRANSLATE_TYPE translate;
5941 const int multibyte;
5943 register re_char *p1 = s1, *p2 = s2;
5944 re_char *p1_end = s1 + len;
5945 re_char *p2_end = s2 + len;
5947 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5948 different lengths, but relying on a single `len' would break this. -sm */
5949 while (p1 < p1_end && p2 < p2_end)
5951 int p1_charlen, p2_charlen;
5952 re_wchar_t p1_ch, p2_ch;
5954 p1_ch = RE_STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5955 p2_ch = RE_STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5957 if (RE_TRANSLATE (translate, p1_ch)
5958 != RE_TRANSLATE (translate, p2_ch))
5959 return 1;
5961 p1 += p1_charlen, p2 += p2_charlen;
5964 if (p1 != p1_end || p2 != p2_end)
5965 return 1;
5967 return 0;
5970 /* Entry points for GNU code. */
5972 /* re_compile_pattern is the GNU regular expression compiler: it
5973 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5974 Returns 0 if the pattern was valid, otherwise an error string.
5976 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5977 are set in BUFP on entry.
5979 We call regex_compile to do the actual compilation. */
5981 const char *
5982 re_compile_pattern (pattern, length, bufp)
5983 const char *pattern;
5984 size_t length;
5985 struct re_pattern_buffer *bufp;
5987 reg_errcode_t ret;
5989 /* GNU code is written to assume at least RE_NREGS registers will be set
5990 (and at least one extra will be -1). */
5991 bufp->regs_allocated = REGS_UNALLOCATED;
5993 /* And GNU code determines whether or not to get register information
5994 by passing null for the REGS argument to re_match, etc., not by
5995 setting no_sub. */
5996 bufp->no_sub = 0;
5998 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6000 if (!ret)
6001 return NULL;
6002 return gettext (re_error_msgid[(int) ret]);
6004 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6006 /* Entry points compatible with 4.2 BSD regex library. We don't define
6007 them unless specifically requested. */
6009 #if defined _REGEX_RE_COMP || defined _LIBC
6011 /* BSD has one and only one pattern buffer. */
6012 static struct re_pattern_buffer re_comp_buf;
6014 char *
6015 # ifdef _LIBC
6016 /* Make these definitions weak in libc, so POSIX programs can redefine
6017 these names if they don't use our functions, and still use
6018 regcomp/regexec below without link errors. */
6019 weak_function
6020 # endif
6021 re_comp (s)
6022 const char *s;
6024 reg_errcode_t ret;
6026 if (!s)
6028 if (!re_comp_buf.buffer)
6029 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6030 return (char *) gettext ("No previous regular expression");
6031 return 0;
6034 if (!re_comp_buf.buffer)
6036 re_comp_buf.buffer = (unsigned char *) malloc (200);
6037 if (re_comp_buf.buffer == NULL)
6038 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6039 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6040 re_comp_buf.allocated = 200;
6042 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6043 if (re_comp_buf.fastmap == NULL)
6044 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6045 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6048 /* Since `re_exec' always passes NULL for the `regs' argument, we
6049 don't need to initialize the pattern buffer fields which affect it. */
6051 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6053 if (!ret)
6054 return NULL;
6056 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6057 return (char *) gettext (re_error_msgid[(int) ret]);
6062 # ifdef _LIBC
6063 weak_function
6064 # endif
6065 re_exec (s)
6066 const char *s;
6068 const int len = strlen (s);
6069 return
6070 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6072 #endif /* _REGEX_RE_COMP */
6074 /* POSIX.2 functions. Don't define these for Emacs. */
6076 #ifndef emacs
6078 /* regcomp takes a regular expression as a string and compiles it.
6080 PREG is a regex_t *. We do not expect any fields to be initialized,
6081 since POSIX says we shouldn't. Thus, we set
6083 `buffer' to the compiled pattern;
6084 `used' to the length of the compiled pattern;
6085 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6086 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6087 RE_SYNTAX_POSIX_BASIC;
6088 `fastmap' to an allocated space for the fastmap;
6089 `fastmap_accurate' to zero;
6090 `re_nsub' to the number of subexpressions in PATTERN.
6092 PATTERN is the address of the pattern string.
6094 CFLAGS is a series of bits which affect compilation.
6096 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6097 use POSIX basic syntax.
6099 If REG_NEWLINE is set, then . and [^...] don't match newline.
6100 Also, regexec will try a match beginning after every newline.
6102 If REG_ICASE is set, then we considers upper- and lowercase
6103 versions of letters to be equivalent when matching.
6105 If REG_NOSUB is set, then when PREG is passed to regexec, that
6106 routine will report only success or failure, and nothing about the
6107 registers.
6109 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6110 the return codes and their meanings.) */
6113 regcomp (preg, pattern, cflags)
6114 regex_t *__restrict preg;
6115 const char *__restrict pattern;
6116 int cflags;
6118 reg_errcode_t ret;
6119 reg_syntax_t syntax
6120 = (cflags & REG_EXTENDED) ?
6121 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6123 /* regex_compile will allocate the space for the compiled pattern. */
6124 preg->buffer = 0;
6125 preg->allocated = 0;
6126 preg->used = 0;
6128 /* Try to allocate space for the fastmap. */
6129 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6131 if (cflags & REG_ICASE)
6133 unsigned i;
6135 preg->translate
6136 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6137 * sizeof (*(RE_TRANSLATE_TYPE)0));
6138 if (preg->translate == NULL)
6139 return (int) REG_ESPACE;
6141 /* Map uppercase characters to corresponding lowercase ones. */
6142 for (i = 0; i < CHAR_SET_SIZE; i++)
6143 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6145 else
6146 preg->translate = NULL;
6148 /* If REG_NEWLINE is set, newlines are treated differently. */
6149 if (cflags & REG_NEWLINE)
6150 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6151 syntax &= ~RE_DOT_NEWLINE;
6152 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6154 else
6155 syntax |= RE_NO_NEWLINE_ANCHOR;
6157 preg->no_sub = !!(cflags & REG_NOSUB);
6159 /* POSIX says a null character in the pattern terminates it, so we
6160 can use strlen here in compiling the pattern. */
6161 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6163 /* POSIX doesn't distinguish between an unmatched open-group and an
6164 unmatched close-group: both are REG_EPAREN. */
6165 if (ret == REG_ERPAREN)
6166 ret = REG_EPAREN;
6168 if (ret == REG_NOERROR && preg->fastmap)
6169 { /* Compute the fastmap now, since regexec cannot modify the pattern
6170 buffer. */
6171 re_compile_fastmap (preg);
6172 if (preg->can_be_null)
6173 { /* The fastmap can't be used anyway. */
6174 free (preg->fastmap);
6175 preg->fastmap = NULL;
6178 return (int) ret;
6180 WEAK_ALIAS (__regcomp, regcomp)
6183 /* regexec searches for a given pattern, specified by PREG, in the
6184 string STRING.
6186 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6187 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6188 least NMATCH elements, and we set them to the offsets of the
6189 corresponding matched substrings.
6191 EFLAGS specifies `execution flags' which affect matching: if
6192 REG_NOTBOL is set, then ^ does not match at the beginning of the
6193 string; if REG_NOTEOL is set, then $ does not match at the end.
6195 We return 0 if we find a match and REG_NOMATCH if not. */
6198 regexec (preg, string, nmatch, pmatch, eflags)
6199 const regex_t *__restrict preg;
6200 const char *__restrict string;
6201 size_t nmatch;
6202 regmatch_t pmatch[__restrict_arr];
6203 int eflags;
6205 int ret;
6206 struct re_registers regs;
6207 regex_t private_preg;
6208 int len = strlen (string);
6209 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6211 private_preg = *preg;
6213 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6214 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6216 /* The user has told us exactly how many registers to return
6217 information about, via `nmatch'. We have to pass that on to the
6218 matching routines. */
6219 private_preg.regs_allocated = REGS_FIXED;
6221 if (want_reg_info)
6223 regs.num_regs = nmatch;
6224 regs.start = TALLOC (nmatch * 2, regoff_t);
6225 if (regs.start == NULL)
6226 return (int) REG_NOMATCH;
6227 regs.end = regs.start + nmatch;
6230 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6231 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6232 was a little bit longer but still only matching the real part.
6233 This works because the `endline' will check for a '\n' and will find a
6234 '\0', correctly deciding that this is not the end of a line.
6235 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6236 a convenient '\0' there. For all we know, the string could be preceded
6237 by '\n' which would throw things off. */
6239 /* Perform the searching operation. */
6240 ret = re_search (&private_preg, string, len,
6241 /* start: */ 0, /* range: */ len,
6242 want_reg_info ? &regs : (struct re_registers *) 0);
6244 /* Copy the register information to the POSIX structure. */
6245 if (want_reg_info)
6247 if (ret >= 0)
6249 unsigned r;
6251 for (r = 0; r < nmatch; r++)
6253 pmatch[r].rm_so = regs.start[r];
6254 pmatch[r].rm_eo = regs.end[r];
6258 /* If we needed the temporary register info, free the space now. */
6259 free (regs.start);
6262 /* We want zero return to mean success, unlike `re_search'. */
6263 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6265 WEAK_ALIAS (__regexec, regexec)
6268 /* Returns a message corresponding to an error code, ERRCODE, returned
6269 from either regcomp or regexec. We don't use PREG here. */
6271 size_t
6272 regerror (errcode, preg, errbuf, errbuf_size)
6273 int errcode;
6274 const regex_t *preg;
6275 char *errbuf;
6276 size_t errbuf_size;
6278 const char *msg;
6279 size_t msg_size;
6281 if (errcode < 0
6282 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6283 /* Only error codes returned by the rest of the code should be passed
6284 to this routine. If we are given anything else, or if other regex
6285 code generates an invalid error code, then the program has a bug.
6286 Dump core so we can fix it. */
6287 abort ();
6289 msg = gettext (re_error_msgid[errcode]);
6291 msg_size = strlen (msg) + 1; /* Includes the null. */
6293 if (errbuf_size != 0)
6295 if (msg_size > errbuf_size)
6297 strncpy (errbuf, msg, errbuf_size - 1);
6298 errbuf[errbuf_size - 1] = 0;
6300 else
6301 strcpy (errbuf, msg);
6304 return msg_size;
6306 WEAK_ALIAS (__regerror, regerror)
6309 /* Free dynamically allocated space used by PREG. */
6311 void
6312 regfree (preg)
6313 regex_t *preg;
6315 if (preg->buffer != NULL)
6316 free (preg->buffer);
6317 preg->buffer = NULL;
6319 preg->allocated = 0;
6320 preg->used = 0;
6322 if (preg->fastmap != NULL)
6323 free (preg->fastmap);
6324 preg->fastmap = NULL;
6325 preg->fastmap_accurate = 0;
6327 if (preg->translate != NULL)
6328 free (preg->translate);
6329 preg->translate = NULL;
6331 WEAK_ALIAS (__regfree, regfree)
6333 #endif /* not emacs */