1 /* Extended regular expression matching and search library,
3 (Implements POSIX draft P1003.2/D11.2, except for some of the
4 internationalization features.)
5 Copyright (C) 1993, 94, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 The GNU C Library 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 GNU
15 Library General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with the GNU C Library; see the file COPYING.LIB. If not,
19 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* AIX requires this to be the first thing in the file. */
23 #if defined _AIX && !defined REGEX_MALLOC
35 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
36 # define PARAMS(args) args
38 # define PARAMS(args) ()
40 #endif /* Not PARAMS. */
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 #define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
51 /* For platform which support the ISO C amendement 1 functionality we
52 support user defined character classes. */
53 #if defined _LIBC || WIDE_CHAR_SUPPORT
54 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
60 /* We have to keep the namespace clean. */
61 # define regfree(preg) __regfree (preg)
62 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
63 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
64 # define regerror(errcode, preg, errbuf, errbuf_size) \
65 __regerror(errcode, preg, errbuf, errbuf_size)
66 # define re_set_registers(bu, re, nu, st, en) \
67 __re_set_registers (bu, re, nu, st, en)
68 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
69 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
70 # define re_match(bufp, string, size, pos, regs) \
71 __re_match (bufp, string, size, pos, regs)
72 # define re_search(bufp, string, size, startpos, range, regs) \
73 __re_search (bufp, string, size, startpos, range, regs)
74 # define re_compile_pattern(pattern, length, bufp) \
75 __re_compile_pattern (pattern, length, bufp)
76 # define re_set_syntax(syntax) __re_set_syntax (syntax)
77 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
78 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
79 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
84 /* This is for other GNU distributions with internationalized messages. */
85 #if HAVE_LIBINTL_H || defined _LIBC
88 # define gettext(msgid) (msgid)
92 /* This define is so xgettext can find the internationalizable
94 # define gettext_noop(String) String
97 /* The `emacs' switch turns on certain matching commands
98 that make sense only in Emacs. */
105 #else /* not emacs */
107 /* If we are not linking with Emacs proper,
108 we can't use the relocating allocator
109 even if config.h says that we can. */
112 # if defined STDC_HEADERS || defined _LIBC
119 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
120 If nothing else has been done, use the method below. */
121 # ifdef INHIBIT_STRING_HEADER
122 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
123 # if !defined bzero && !defined bcopy
124 # undef INHIBIT_STRING_HEADER
129 /* This is the normal way of making sure we have a bcopy and a bzero.
130 This is used in most programs--a few other programs avoid this
131 by defining INHIBIT_STRING_HEADER. */
132 # ifndef INHIBIT_STRING_HEADER
133 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
137 # define bzero(s, n) (memset (s, '\0', n), (s))
139 # define bzero(s, n) __bzero (s, n)
143 # include <strings.h>
145 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
148 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
153 /* Define the syntax stuff for \<, \>, etc. */
155 /* This must be nonzero for the wordchar and notwordchar pattern
156 commands in re_match_2. */
161 # ifdef SWITCH_ENUM_BUG
162 # define SWITCH_ENUM_CAST(x) ((int)(x))
164 # define SWITCH_ENUM_CAST(x) (x)
167 #endif /* not emacs */
169 /* Get the interface, including the syntax bits. */
172 /* isalpha etc. are used for the character classes. */
175 /* Jim Meyering writes:
177 "... Some ctype macros are valid only for character codes that
178 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
179 using /bin/cc or gcc but without giving an ansi option). So, all
180 ctype uses should be through macros like ISPRINT... If
181 STDC_HEADERS is defined, then autoconf has verified that the ctype
182 macros don't need to be guarded with references to isascii. ...
183 Defining isascii to 1 should let any compiler worth its salt
184 eliminate the && through constant folding."
185 Solaris defines some of these symbols so we must undefine them first. */
188 #if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
189 # define ISASCII(c) 1
191 # define ISASCII(c) isascii(c)
195 # define ISBLANK(c) (ISASCII (c) && isblank (c))
197 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
200 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
202 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
206 #define ISPRINT(c) (ISASCII (c) && isprint (c))
207 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
208 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
209 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
210 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
211 #define ISLOWER(c) (ISASCII (c) && islower (c))
212 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
213 #define ISSPACE(c) (ISASCII (c) && isspace (c))
214 #define ISUPPER(c) (ISASCII (c) && isupper (c))
215 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
218 # define TOLOWER(c) _tolower(c)
220 # define TOLOWER(c) tolower(c)
224 # define NULL (void *)0
227 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
228 since ours (we hope) works properly with all combinations of
229 machines, compilers, `char' and `unsigned char' argument types.
230 (Per Bothner suggested the basic approach.) */
231 #undef SIGN_EXTEND_CHAR
233 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
234 #else /* not __STDC__ */
235 /* As in Harbison and Steele. */
236 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
240 /* How many characters in the character set. */
241 # define CHAR_SET_SIZE 256
245 extern char *re_syntax_table
;
247 # else /* not SYNTAX_TABLE */
249 static char re_syntax_table
[CHAR_SET_SIZE
];
259 bzero (re_syntax_table
, sizeof re_syntax_table
);
261 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
263 re_syntax_table
[c
] = Sword
;
265 re_syntax_table
['_'] = Sword
;
270 # endif /* not SYNTAX_TABLE */
272 # define SYNTAX(c) re_syntax_table[((c) & 0xFF)]
276 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
277 use `alloca' instead of `malloc'. This is because using malloc in
278 re_search* or re_match* could cause memory leaks when C-g is used in
279 Emacs; also, malloc is slower and causes storage fragmentation. On
280 the other hand, malloc is more portable, and easier to debug.
282 Because we sometimes use alloca, some routines have to be macros,
283 not functions -- `alloca'-allocated space disappears at the end of the
284 function it is called in. */
288 # define REGEX_ALLOCATE malloc
289 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
290 # define REGEX_FREE free
292 #else /* not REGEX_MALLOC */
294 /* Emacs already defines alloca, sometimes. */
297 /* Make alloca work the best possible way. */
299 # define alloca __builtin_alloca
300 # else /* not __GNUC__ */
303 # endif /* HAVE_ALLOCA_H */
304 # endif /* not __GNUC__ */
306 # endif /* not alloca */
308 # define REGEX_ALLOCATE alloca
310 /* Assumes a `char *destination' variable. */
311 # define REGEX_REALLOCATE(source, osize, nsize) \
312 (destination = (char *) alloca (nsize), \
313 memcpy (destination, source, osize))
315 /* No need to do anything to free, after alloca. */
316 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
318 #endif /* not REGEX_MALLOC */
320 /* Define how to allocate the failure stack. */
322 #if defined REL_ALLOC && defined REGEX_MALLOC
324 # define REGEX_ALLOCATE_STACK(size) \
325 r_alloc (&failure_stack_ptr, (size))
326 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
327 r_re_alloc (&failure_stack_ptr, (nsize))
328 # define REGEX_FREE_STACK(ptr) \
329 r_alloc_free (&failure_stack_ptr)
331 #else /* not using relocating allocator */
335 # define REGEX_ALLOCATE_STACK malloc
336 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
337 # define REGEX_FREE_STACK free
339 # else /* not REGEX_MALLOC */
341 # define REGEX_ALLOCATE_STACK alloca
343 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
344 REGEX_REALLOCATE (source, osize, nsize)
345 /* No need to explicitly free anything. */
346 # define REGEX_FREE_STACK(arg)
348 # endif /* not REGEX_MALLOC */
349 #endif /* not using relocating allocator */
352 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
353 `string1' or just past its end. This works if PTR is NULL, which is
355 #define FIRST_STRING_P(ptr) \
356 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
358 /* (Re)Allocate N items of type T using malloc, or fail. */
359 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
360 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
361 #define RETALLOC_IF(addr, n, t) \
362 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
363 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
365 #define BYTEWIDTH 8 /* In bits. */
367 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
371 #define MAX(a, b) ((a) > (b) ? (a) : (b))
372 #define MIN(a, b) ((a) < (b) ? (a) : (b))
374 typedef char boolean
;
378 static int re_match_2_internal
PARAMS ((struct re_pattern_buffer
*bufp
,
379 const char *string1
, int size1
,
380 const char *string2
, int size2
,
382 struct re_registers
*regs
,
385 /* These are the command codes that appear in compiled regular
386 expressions. Some opcodes are followed by argument bytes. A
387 command code can specify any interpretation whatsoever for its
388 arguments. Zero bytes may appear in the compiled regular expression. */
394 /* Succeed right away--no more backtracking. */
397 /* Followed by one byte giving n, then by n literal bytes. */
400 /* Matches any (more or less) character. */
403 /* Matches any one char belonging to specified set. First
404 following byte is number of bitmap bytes. Then come bytes
405 for a bitmap saying which chars are in. Bits in each byte
406 are ordered low-bit-first. A character is in the set if its
407 bit is 1. A character too large to have a bit in the map is
408 automatically not in the set. */
411 /* Same parameters as charset, but match any character that is
412 not one of those specified. */
415 /* Start remembering the text that is matched, for storing in a
416 register. Followed by one byte with the register number, in
417 the range 0 to one less than the pattern buffer's re_nsub
418 field. Then followed by one byte with the number of groups
419 inner to this one. (This last has to be part of the
420 start_memory only because we need it in the on_failure_jump
424 /* Stop remembering the text that is matched and store it in a
425 memory register. Followed by one byte with the register
426 number, in the range 0 to one less than `re_nsub' in the
427 pattern buffer, and one byte with the number of inner groups,
428 just like `start_memory'. (We need the number of inner
429 groups here because we don't have any easy way of finding the
430 corresponding start_memory when we're at a stop_memory.) */
433 /* Match a duplicate of something remembered. Followed by one
434 byte containing the register number. */
437 /* Fail unless at beginning of line. */
440 /* Fail unless at end of line. */
443 /* Succeeds if at beginning of buffer (if emacs) or at beginning
444 of string to be matched (if not). */
447 /* Analogously, for end of buffer/string. */
450 /* Followed by two byte relative address to which to jump. */
453 /* Same as jump, but marks the end of an alternative. */
456 /* Followed by two-byte relative address of place to resume at
457 in case of failure. */
460 /* Like on_failure_jump, but pushes a placeholder instead of the
461 current string position when executed. */
462 on_failure_keep_string_jump
,
464 /* Throw away latest failure point and then jump to following
465 two-byte relative address. */
468 /* Change to pop_failure_jump if know won't have to backtrack to
469 match; otherwise change to jump. This is used to jump
470 back to the beginning of a repeat. If what follows this jump
471 clearly won't match what the repeat does, such that we can be
472 sure that there is no use backtracking out of repetitions
473 already matched, then we change it to a pop_failure_jump.
474 Followed by two-byte address. */
477 /* Jump to following two-byte address, and push a dummy failure
478 point. This failure point will be thrown away if an attempt
479 is made to use it for a failure. A `+' construct makes this
480 before the first repeat. Also used as an intermediary kind
481 of jump when compiling an alternative. */
484 /* Push a dummy failure point and continue. Used at the end of
488 /* Followed by two-byte relative address and two-byte number n.
489 After matching N times, jump to the address upon failure. */
492 /* Followed by two-byte relative address, and two-byte number n.
493 Jump to the address N times, then fail. */
496 /* Set the following two-byte relative address to the
497 subsequent two-byte number. The address *includes* the two
501 wordchar
, /* Matches any word-constituent character. */
502 notwordchar
, /* Matches any char that is not a word-constituent. */
504 wordbeg
, /* Succeeds if at word beginning. */
505 wordend
, /* Succeeds if at word end. */
507 wordbound
, /* Succeeds if at a word boundary. */
508 notwordbound
/* Succeeds if not at a word boundary. */
511 ,before_dot
, /* Succeeds if before point. */
512 at_dot
, /* Succeeds if at point. */
513 after_dot
, /* Succeeds if after point. */
515 /* Matches any character whose syntax is specified. Followed by
516 a byte which contains a syntax code, e.g., Sword. */
519 /* Matches any character whose syntax is not that specified. */
524 /* Common operations on the compiled pattern. */
526 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
528 #define STORE_NUMBER(destination, number) \
530 (destination)[0] = (number) & 0377; \
531 (destination)[1] = (number) >> 8; \
534 /* Same as STORE_NUMBER, except increment DESTINATION to
535 the byte after where the number is stored. Therefore, DESTINATION
536 must be an lvalue. */
538 #define STORE_NUMBER_AND_INCR(destination, number) \
540 STORE_NUMBER (destination, number); \
541 (destination) += 2; \
544 /* Put into DESTINATION a number stored in two contiguous bytes starting
547 #define EXTRACT_NUMBER(destination, source) \
549 (destination) = *(source) & 0377; \
550 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
554 static void extract_number
_RE_ARGS ((int *dest
, unsigned char *source
));
556 extract_number (dest
, source
)
558 unsigned char *source
;
560 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
561 *dest
= *source
& 0377;
565 # ifndef EXTRACT_MACROS /* To debug the macros. */
566 # undef EXTRACT_NUMBER
567 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
568 # endif /* not EXTRACT_MACROS */
572 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
573 SOURCE must be an lvalue. */
575 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
577 EXTRACT_NUMBER (destination, source); \
582 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
583 unsigned char **source
));
585 extract_number_and_incr (destination
, source
)
587 unsigned char **source
;
589 extract_number (destination
, *source
);
593 # ifndef EXTRACT_MACROS
594 # undef EXTRACT_NUMBER_AND_INCR
595 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
596 extract_number_and_incr (&dest, &src)
597 # endif /* not EXTRACT_MACROS */
601 /* If DEBUG is defined, Regex prints many voluminous messages about what
602 it is doing (if the variable `debug' is nonzero). If linked with the
603 main program in `iregex.c', you can enter patterns and strings
604 interactively. And if linked with the main program in `main.c' and
605 the other test files, you can run the already-written tests. */
609 /* We use standard I/O for debugging. */
612 /* It is useful to test things that ``must'' be true when debugging. */
617 # define DEBUG_STATEMENT(e) e
618 # define DEBUG_PRINT1(x) if (debug) printf (x)
619 # define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
620 # define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
621 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
622 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
623 if (debug) print_partial_compiled_pattern (s, e)
624 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
625 if (debug) print_double_string (w, s1, sz1, s2, sz2)
628 /* Print the fastmap in human-readable form. */
631 print_fastmap (fastmap
)
634 unsigned was_a_range
= 0;
637 while (i
< (1 << BYTEWIDTH
))
643 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
659 /* Print a compiled pattern string in human-readable form, starting at
660 the START pointer into it and ending just before the pointer END. */
663 print_partial_compiled_pattern (start
, end
)
664 unsigned char *start
;
669 unsigned char *p
= start
;
670 unsigned char *pend
= end
;
678 /* Loop over pattern commands. */
681 printf ("%d:\t", p
- start
);
683 switch ((re_opcode_t
) *p
++)
691 printf ("/exactn/%d", mcnt
);
702 printf ("/start_memory/%d/%d", mcnt
, *p
++);
707 printf ("/stop_memory/%d/%d", mcnt
, *p
++);
711 printf ("/duplicate/%d", *p
++);
721 register int c
, last
= -100;
722 register int in_range
= 0;
724 printf ("/charset [%s",
725 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
727 assert (p
+ *p
< pend
);
729 for (c
= 0; c
< 256; c
++)
731 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
733 /* Are we starting a range? */
734 if (last
+ 1 == c
&& ! in_range
)
739 /* Have we broken a range? */
740 else if (last
+ 1 != c
&& in_range
)
769 case on_failure_jump
:
770 extract_number_and_incr (&mcnt
, &p
);
771 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
774 case on_failure_keep_string_jump
:
775 extract_number_and_incr (&mcnt
, &p
);
776 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
779 case dummy_failure_jump
:
780 extract_number_and_incr (&mcnt
, &p
);
781 printf ("/dummy_failure_jump to %d", p
+ mcnt
- start
);
784 case push_dummy_failure
:
785 printf ("/push_dummy_failure");
789 extract_number_and_incr (&mcnt
, &p
);
790 printf ("/maybe_pop_jump to %d", p
+ mcnt
- start
);
793 case pop_failure_jump
:
794 extract_number_and_incr (&mcnt
, &p
);
795 printf ("/pop_failure_jump to %d", p
+ mcnt
- start
);
799 extract_number_and_incr (&mcnt
, &p
);
800 printf ("/jump_past_alt to %d", p
+ mcnt
- start
);
804 extract_number_and_incr (&mcnt
, &p
);
805 printf ("/jump to %d", p
+ mcnt
- start
);
809 extract_number_and_incr (&mcnt
, &p
);
811 extract_number_and_incr (&mcnt2
, &p
);
812 printf ("/succeed_n to %d, %d times", p1
- start
, mcnt2
);
816 extract_number_and_incr (&mcnt
, &p
);
818 extract_number_and_incr (&mcnt2
, &p
);
819 printf ("/jump_n to %d, %d times", p1
- start
, mcnt2
);
823 extract_number_and_incr (&mcnt
, &p
);
825 extract_number_and_incr (&mcnt2
, &p
);
826 printf ("/set_number_at location %d to %d", p1
- start
, mcnt2
);
830 printf ("/wordbound");
834 printf ("/notwordbound");
846 printf ("/before_dot");
854 printf ("/after_dot");
858 printf ("/syntaxspec");
860 printf ("/%d", mcnt
);
864 printf ("/notsyntaxspec");
866 printf ("/%d", mcnt
);
871 printf ("/wordchar");
875 printf ("/notwordchar");
887 printf ("?%d", *(p
-1));
893 printf ("%d:\tend of pattern.\n", p
- start
);
898 print_compiled_pattern (bufp
)
899 struct re_pattern_buffer
*bufp
;
901 unsigned char *buffer
= bufp
->buffer
;
903 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
904 printf ("%ld bytes used/%ld bytes allocated.\n",
905 bufp
->used
, bufp
->allocated
);
907 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
909 printf ("fastmap: ");
910 print_fastmap (bufp
->fastmap
);
913 printf ("re_nsub: %d\t", bufp
->re_nsub
);
914 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
915 printf ("can_be_null: %d\t", bufp
->can_be_null
);
916 printf ("newline_anchor: %d\n", bufp
->newline_anchor
);
917 printf ("no_sub: %d\t", bufp
->no_sub
);
918 printf ("not_bol: %d\t", bufp
->not_bol
);
919 printf ("not_eol: %d\t", bufp
->not_eol
);
920 printf ("syntax: %lx\n", bufp
->syntax
);
921 /* Perhaps we should print the translate table? */
926 print_double_string (where
, string1
, size1
, string2
, size2
)
939 if (FIRST_STRING_P (where
))
941 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
942 putchar (string1
[this_char
]);
947 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
948 putchar (string2
[this_char
]);
959 #else /* not DEBUG */
964 # define DEBUG_STATEMENT(e)
965 # define DEBUG_PRINT1(x)
966 # define DEBUG_PRINT2(x1, x2)
967 # define DEBUG_PRINT3(x1, x2, x3)
968 # define DEBUG_PRINT4(x1, x2, x3, x4)
969 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
970 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
972 #endif /* not DEBUG */
974 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
975 also be assigned to arbitrarily: each pattern buffer stores its own
976 syntax, so it can be changed between regex compilations. */
977 /* This has no initializer because initialized variables in Emacs
978 become read-only after dumping. */
979 reg_syntax_t re_syntax_options
;
982 /* Specify the precise syntax of regexps for compilation. This provides
983 for compatibility for various utilities which historically have
984 different, incompatible syntaxes.
986 The argument SYNTAX is a bit mask comprised of the various bits
987 defined in regex.h. We return the old syntax. */
990 re_set_syntax (syntax
)
993 reg_syntax_t ret
= re_syntax_options
;
995 re_syntax_options
= syntax
;
997 if (syntax
& RE_DEBUG
)
999 else if (debug
) /* was on but now is not */
1005 weak_alias (__re_set_syntax
, re_set_syntax
)
1008 /* This table gives an error message for each of the error codes listed
1009 in regex.h. Obviously the order here has to be same as there.
1010 POSIX doesn't require that we do anything for REG_NOERROR,
1011 but why not be nice? */
1013 static const char re_error_msgid
[] =
1015 #define REG_NOERROR_IDX 0
1016 gettext_noop ("Success") /* REG_NOERROR */
1018 #define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1019 gettext_noop ("No match") /* REG_NOMATCH */
1021 #define REG_BADPAT_IDX (REG_NOMATCH_IDX + sizeof "No match")
1022 gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1024 #define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1025 gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1027 #define REG_ECTYPE_IDX (REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1028 gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1030 #define REG_EESCAPE_IDX (REG_ECTYPE_IDX + sizeof "Invalid character class name")
1031 gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1033 #define REG_ESUBREG_IDX (REG_EESCAPE_IDX + sizeof "Trailing backslash")
1034 gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1036 #define REG_EBRACK_IDX (REG_ESUBREG_IDX + sizeof "Invalid back reference")
1037 gettext_noop ("Unmatched [ or [^") /* REG_EBRACK */
1039 #define REG_EPAREN_IDX (REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1040 gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1042 #define REG_EBRACE_IDX (REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1043 gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1045 #define REG_BADBR_IDX (REG_EBRACE_IDX + sizeof "Unmatched \\{")
1046 gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1048 #define REG_ERANGE_IDX (REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1049 gettext_noop ("Invalid range end") /* REG_ERANGE */
1051 #define REG_ESPACE_IDX (REG_ERANGE_IDX + sizeof "Invalid range end")
1052 gettext_noop ("Memory exhausted") /* REG_ESPACE */
1054 #define REG_BADRPT_IDX (REG_ESPACE_IDX + sizeof "Memory exhausted")
1055 gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1057 #define REG_EEND_IDX (REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1058 gettext_noop ("Premature end of regular expression") /* REG_EEND */
1060 #define REG_ESIZE_IDX (REG_EEND_IDX + sizeof "Premature end of regular expression")
1061 gettext_noop ("Regular expression too big") /* REG_ESIZE */
1063 #define REG_ERPAREN_IDX (REG_ESIZE_IDX + sizeof "Regular expression too big")
1064 gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1067 static const size_t re_error_msgid_idx
[] =
1088 /* Avoiding alloca during matching, to placate r_alloc. */
1090 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1091 searching and matching functions should not call alloca. On some
1092 systems, alloca is implemented in terms of malloc, and if we're
1093 using the relocating allocator routines, then malloc could cause a
1094 relocation, which might (if the strings being searched are in the
1095 ralloc heap) shift the data out from underneath the regexp
1098 Here's another reason to avoid allocation: Emacs
1099 processes input from X in a signal handler; processing X input may
1100 call malloc; if input arrives while a matching routine is calling
1101 malloc, then we're scrod. But Emacs can't just block input while
1102 calling matching routines; then we don't notice interrupts when
1103 they come in. So, Emacs blocks input around all regexp calls
1104 except the matching calls, which it leaves unprotected, in the
1105 faith that they will not malloc. */
1107 /* Normally, this is fine. */
1108 #define MATCH_MAY_ALLOCATE
1110 /* When using GNU C, we are not REALLY using the C alloca, no matter
1111 what config.h may say. So don't take precautions for it. */
1116 /* The match routines may not allocate if (1) they would do it with malloc
1117 and (2) it's not safe for them to use malloc.
1118 Note that if REL_ALLOC is defined, matching would not use malloc for the
1119 failure stack, but we would still use it for the register vectors;
1120 so REL_ALLOC should not affect this. */
1121 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1122 # undef MATCH_MAY_ALLOCATE
1126 /* Failure stack declarations and macros; both re_compile_fastmap and
1127 re_match_2 use a failure stack. These have to be macros because of
1128 REGEX_ALLOCATE_STACK. */
1131 /* Number of failure points for which to initially allocate space
1132 when matching. If this number is exceeded, we allocate more
1133 space, so it is not a hard limit. */
1134 #ifndef INIT_FAILURE_ALLOC
1135 # define INIT_FAILURE_ALLOC 5
1138 /* Roughly the maximum number of failure points on the stack. Would be
1139 exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1140 This is a variable only so users of regex can assign to it; we never
1141 change it ourselves. */
1145 # if defined MATCH_MAY_ALLOCATE
1146 /* 4400 was enough to cause a crash on Alpha OSF/1,
1147 whose default stack limit is 2mb. */
1148 long int re_max_failures
= 4000;
1150 long int re_max_failures
= 2000;
1153 union fail_stack_elt
1155 unsigned char *pointer
;
1159 typedef union fail_stack_elt fail_stack_elt_t
;
1163 fail_stack_elt_t
*stack
;
1164 unsigned long int size
;
1165 unsigned long int avail
; /* Offset of next open position. */
1168 #else /* not INT_IS_16BIT */
1170 # if defined MATCH_MAY_ALLOCATE
1171 /* 4400 was enough to cause a crash on Alpha OSF/1,
1172 whose default stack limit is 2mb. */
1173 int re_max_failures
= 20000;
1175 int re_max_failures
= 2000;
1178 union fail_stack_elt
1180 unsigned char *pointer
;
1184 typedef union fail_stack_elt fail_stack_elt_t
;
1188 fail_stack_elt_t
*stack
;
1190 unsigned avail
; /* Offset of next open position. */
1193 #endif /* INT_IS_16BIT */
1195 #define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
1196 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1197 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1200 /* Define macros to initialize and free the failure stack.
1201 Do `return -2' if the alloc fails. */
1203 #ifdef MATCH_MAY_ALLOCATE
1204 # define INIT_FAIL_STACK() \
1206 fail_stack.stack = (fail_stack_elt_t *) \
1207 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1209 if (fail_stack.stack == NULL) \
1212 fail_stack.size = INIT_FAILURE_ALLOC; \
1213 fail_stack.avail = 0; \
1216 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1218 # define INIT_FAIL_STACK() \
1220 fail_stack.avail = 0; \
1223 # define RESET_FAIL_STACK()
1227 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1229 Return 1 if succeeds, and 0 if either ran out of memory
1230 allocating space for it or it was already too large.
1232 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1234 #define DOUBLE_FAIL_STACK(fail_stack) \
1235 ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS) \
1237 : ((fail_stack).stack = (fail_stack_elt_t *) \
1238 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1239 (fail_stack).size * sizeof (fail_stack_elt_t), \
1240 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
1242 (fail_stack).stack == NULL \
1244 : ((fail_stack).size <<= 1, \
1248 /* Push pointer POINTER on FAIL_STACK.
1249 Return 1 if was able to do so and 0 if ran out of memory allocating
1251 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1252 ((FAIL_STACK_FULL () \
1253 && !DOUBLE_FAIL_STACK (FAIL_STACK)) \
1255 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1258 /* Push a pointer value onto the failure stack.
1259 Assumes the variable `fail_stack'. Probably should only
1260 be called from within `PUSH_FAILURE_POINT'. */
1261 #define PUSH_FAILURE_POINTER(item) \
1262 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1264 /* This pushes an integer-valued item onto the failure stack.
1265 Assumes the variable `fail_stack'. Probably should only
1266 be called from within `PUSH_FAILURE_POINT'. */
1267 #define PUSH_FAILURE_INT(item) \
1268 fail_stack.stack[fail_stack.avail++].integer = (item)
1270 /* Push a fail_stack_elt_t value onto the failure stack.
1271 Assumes the variable `fail_stack'. Probably should only
1272 be called from within `PUSH_FAILURE_POINT'. */
1273 #define PUSH_FAILURE_ELT(item) \
1274 fail_stack.stack[fail_stack.avail++] = (item)
1276 /* These three POP... operations complement the three PUSH... operations.
1277 All assume that `fail_stack' is nonempty. */
1278 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1279 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1280 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1282 /* Used to omit pushing failure point id's when we're not debugging. */
1284 # define DEBUG_PUSH PUSH_FAILURE_INT
1285 # define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1287 # define DEBUG_PUSH(item)
1288 # define DEBUG_POP(item_addr)
1292 /* Push the information about the state we will need
1293 if we ever fail back to it.
1295 Requires variables fail_stack, regstart, regend, reg_info, and
1296 num_regs_pushed be declared. DOUBLE_FAIL_STACK requires `destination'
1299 Does `return FAILURE_CODE' if runs out of memory. */
1301 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
1303 char *destination; \
1304 /* Must be int, so when we don't save any registers, the arithmetic \
1305 of 0 + -1 isn't done as unsigned. */ \
1306 /* Can't be int, since there is not a shred of a guarantee that int \
1307 is wide enough to hold a value of something to which pointer can \
1309 active_reg_t this_reg; \
1311 DEBUG_STATEMENT (failure_id++); \
1312 DEBUG_STATEMENT (nfailure_points_pushed++); \
1313 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1314 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
1315 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1317 DEBUG_PRINT2 (" slots needed: %ld\n", NUM_FAILURE_ITEMS); \
1318 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
1320 /* Ensure we have enough space allocated for what we will push. */ \
1321 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
1323 if (!DOUBLE_FAIL_STACK (fail_stack)) \
1324 return failure_code; \
1326 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
1327 (fail_stack).size); \
1328 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1331 /* Push the info, starting with the registers. */ \
1332 DEBUG_PRINT1 ("\n"); \
1335 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1338 DEBUG_PRINT2 (" Pushing reg: %lu\n", this_reg); \
1339 DEBUG_STATEMENT (num_regs_pushed++); \
1341 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1342 PUSH_FAILURE_POINTER (regstart[this_reg]); \
1344 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1345 PUSH_FAILURE_POINTER (regend[this_reg]); \
1347 DEBUG_PRINT2 (" info: %p\n ", \
1348 reg_info[this_reg].word.pointer); \
1349 DEBUG_PRINT2 (" match_null=%d", \
1350 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
1351 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
1352 DEBUG_PRINT2 (" matched_something=%d", \
1353 MATCHED_SOMETHING (reg_info[this_reg])); \
1354 DEBUG_PRINT2 (" ever_matched=%d", \
1355 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
1356 DEBUG_PRINT1 ("\n"); \
1357 PUSH_FAILURE_ELT (reg_info[this_reg].word); \
1360 DEBUG_PRINT2 (" Pushing low active reg: %ld\n", lowest_active_reg);\
1361 PUSH_FAILURE_INT (lowest_active_reg); \
1363 DEBUG_PRINT2 (" Pushing high active reg: %ld\n", highest_active_reg);\
1364 PUSH_FAILURE_INT (highest_active_reg); \
1366 DEBUG_PRINT2 (" Pushing pattern %p:\n", pattern_place); \
1367 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
1368 PUSH_FAILURE_POINTER (pattern_place); \
1370 DEBUG_PRINT2 (" Pushing string %p: `", string_place); \
1371 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
1373 DEBUG_PRINT1 ("'\n"); \
1374 PUSH_FAILURE_POINTER (string_place); \
1376 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
1377 DEBUG_PUSH (failure_id); \
1380 /* This is the number of items that are pushed and popped on the stack
1381 for each register. */
1382 #define NUM_REG_ITEMS 3
1384 /* Individual items aside from the registers. */
1386 # define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
1388 # define NUM_NONREG_ITEMS 4
1391 /* We push at most this many items on the stack. */
1392 /* We used to use (num_regs - 1), which is the number of registers
1393 this regexp will save; but that was changed to 5
1394 to avoid stack overflow for a regexp with lots of parens. */
1395 #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1397 /* We actually push this many items. */
1398 #define NUM_FAILURE_ITEMS \
1400 ? 0 : highest_active_reg - lowest_active_reg + 1) \
1404 /* How many items can still be added to the stack without overflowing it. */
1405 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1408 /* Pops what PUSH_FAIL_STACK pushes.
1410 We restore into the parameters, all of which should be lvalues:
1411 STR -- the saved data position.
1412 PAT -- the saved pattern position.
1413 LOW_REG, HIGH_REG -- the highest and lowest active registers.
1414 REGSTART, REGEND -- arrays of string positions.
1415 REG_INFO -- array of information about each subexpression.
1417 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1418 `pend', `string1', `size1', `string2', and `size2'. */
1420 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1422 DEBUG_STATEMENT (unsigned failure_id;) \
1423 active_reg_t this_reg; \
1424 const unsigned char *string_temp; \
1426 assert (!FAIL_STACK_EMPTY ()); \
1428 /* Remove failure points and point to how many regs pushed. */ \
1429 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1430 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1431 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1433 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
1435 DEBUG_POP (&failure_id); \
1436 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
1438 /* If the saved string location is NULL, it came from an \
1439 on_failure_keep_string_jump opcode, and we want to throw away the \
1440 saved NULL, thus retaining our current position in the string. */ \
1441 string_temp = POP_FAILURE_POINTER (); \
1442 if (string_temp != NULL) \
1443 str = (const char *) string_temp; \
1445 DEBUG_PRINT2 (" Popping string %p: `", str); \
1446 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1447 DEBUG_PRINT1 ("'\n"); \
1449 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1450 DEBUG_PRINT2 (" Popping pattern %p:\n", pat); \
1451 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1453 /* Restore register info. */ \
1454 high_reg = (active_reg_t) POP_FAILURE_INT (); \
1455 DEBUG_PRINT2 (" Popping high active reg: %ld\n", high_reg); \
1457 low_reg = (active_reg_t) POP_FAILURE_INT (); \
1458 DEBUG_PRINT2 (" Popping low active reg: %ld\n", low_reg); \
1461 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
1463 DEBUG_PRINT2 (" Popping reg: %ld\n", this_reg); \
1465 reg_info[this_reg].word = POP_FAILURE_ELT (); \
1466 DEBUG_PRINT2 (" info: %p\n", \
1467 reg_info[this_reg].word.pointer); \
1469 regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1470 DEBUG_PRINT2 (" end: %p\n", regend[this_reg]); \
1472 regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \
1473 DEBUG_PRINT2 (" start: %p\n", regstart[this_reg]); \
1477 for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1479 reg_info[this_reg].word.integer = 0; \
1480 regend[this_reg] = 0; \
1481 regstart[this_reg] = 0; \
1483 highest_active_reg = high_reg; \
1486 set_regs_matched_done = 0; \
1487 DEBUG_STATEMENT (nfailure_points_popped++); \
1488 } /* POP_FAILURE_POINT */
1492 /* Structure for per-register (a.k.a. per-group) information.
1493 Other register information, such as the
1494 starting and ending positions (which are addresses), and the list of
1495 inner groups (which is a bits list) are maintained in separate
1498 We are making a (strictly speaking) nonportable assumption here: that
1499 the compiler will pack our bit fields into something that fits into
1500 the type of `word', i.e., is something that fits into one item on the
1504 /* Declarations and macros for re_match_2. */
1508 fail_stack_elt_t word
;
1511 /* This field is one if this group can match the empty string,
1512 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
1513 #define MATCH_NULL_UNSET_VALUE 3
1514 unsigned match_null_string_p
: 2;
1515 unsigned is_active
: 1;
1516 unsigned matched_something
: 1;
1517 unsigned ever_matched_something
: 1;
1519 } register_info_type
;
1521 #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
1522 #define IS_ACTIVE(R) ((R).bits.is_active)
1523 #define MATCHED_SOMETHING(R) ((R).bits.matched_something)
1524 #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
1527 /* Call this when have matched a real character; it sets `matched' flags
1528 for the subexpressions which we are currently inside. Also records
1529 that those subexprs have matched. */
1530 #define SET_REGS_MATCHED() \
1533 if (!set_regs_matched_done) \
1536 set_regs_matched_done = 1; \
1537 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
1539 MATCHED_SOMETHING (reg_info[r]) \
1540 = EVER_MATCHED_SOMETHING (reg_info[r]) \
1547 /* Registers are set to a sentinel when they haven't yet matched. */
1548 static char reg_unset_dummy
;
1549 #define REG_UNSET_VALUE (®_unset_dummy)
1550 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1552 /* Subroutine declarations and macros for regex_compile. */
1554 static reg_errcode_t regex_compile
_RE_ARGS ((const char *pattern
, size_t size
,
1555 reg_syntax_t syntax
,
1556 struct re_pattern_buffer
*bufp
));
1557 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1558 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1559 int arg1
, int arg2
));
1560 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1561 int arg
, unsigned char *end
));
1562 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1563 int arg1
, int arg2
, unsigned char *end
));
1564 static boolean at_begline_loc_p
_RE_ARGS ((const char *pattern
, const char *p
,
1565 reg_syntax_t syntax
));
1566 static boolean at_endline_loc_p
_RE_ARGS ((const char *p
, const char *pend
,
1567 reg_syntax_t syntax
));
1568 static reg_errcode_t compile_range
_RE_ARGS ((const char **p_ptr
,
1571 reg_syntax_t syntax
,
1574 /* Fetch the next character in the uncompiled pattern---translating it
1575 if necessary. Also cast from a signed character in the constant
1576 string passed to us by the user to an unsigned char that we can use
1577 as an array index (in, e.g., `translate'). */
1579 # define PATFETCH(c) \
1580 do {if (p == pend) return REG_EEND; \
1581 c = (unsigned char) *p++; \
1582 if (translate) c = (unsigned char) translate[c]; \
1586 /* Fetch the next character in the uncompiled pattern, with no
1588 #define PATFETCH_RAW(c) \
1589 do {if (p == pend) return REG_EEND; \
1590 c = (unsigned char) *p++; \
1593 /* Go backwards one character in the pattern. */
1594 #define PATUNFETCH p--
1597 /* If `translate' is non-null, return translate[D], else just D. We
1598 cast the subscript to translate because some data is declared as
1599 `char *', to avoid warnings when a string constant is passed. But
1600 when we use a character as a subscript we must make it unsigned. */
1602 # define TRANSLATE(d) \
1603 (translate ? (char) translate[(unsigned char) (d)] : (d))
1607 /* Macros for outputting the compiled pattern into `buffer'. */
1609 /* If the buffer isn't allocated when it comes in, use this. */
1610 #define INIT_BUF_SIZE 32
1612 /* Make sure we have at least N more bytes of space in buffer. */
1613 #define GET_BUFFER_SPACE(n) \
1614 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1617 /* Make sure we have one more byte of buffer space and then add C to it. */
1618 #define BUF_PUSH(c) \
1620 GET_BUFFER_SPACE (1); \
1621 *b++ = (unsigned char) (c); \
1625 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1626 #define BUF_PUSH_2(c1, c2) \
1628 GET_BUFFER_SPACE (2); \
1629 *b++ = (unsigned char) (c1); \
1630 *b++ = (unsigned char) (c2); \
1634 /* As with BUF_PUSH_2, except for three bytes. */
1635 #define BUF_PUSH_3(c1, c2, c3) \
1637 GET_BUFFER_SPACE (3); \
1638 *b++ = (unsigned char) (c1); \
1639 *b++ = (unsigned char) (c2); \
1640 *b++ = (unsigned char) (c3); \
1644 /* Store a jump with opcode OP at LOC to location TO. We store a
1645 relative address offset by the three bytes the jump itself occupies. */
1646 #define STORE_JUMP(op, loc, to) \
1647 store_op1 (op, loc, (int) ((to) - (loc) - 3))
1649 /* Likewise, for a two-argument jump. */
1650 #define STORE_JUMP2(op, loc, to, arg) \
1651 store_op2 (op, loc, (int) ((to) - (loc) - 3), arg)
1653 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1654 #define INSERT_JUMP(op, loc, to) \
1655 insert_op1 (op, loc, (int) ((to) - (loc) - 3), b)
1657 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1658 #define INSERT_JUMP2(op, loc, to, arg) \
1659 insert_op2 (op, loc, (int) ((to) - (loc) - 3), arg, b)
1662 /* This is not an arbitrary limit: the arguments which represent offsets
1663 into the pattern are two bytes long. So if 2^16 bytes turns out to
1664 be too small, many things would have to change. */
1665 /* Any other compiler which, like MSC, has allocation limit below 2^16
1666 bytes will have to use approach similar to what was done below for
1667 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1668 reallocating to 0 bytes. Such thing is not going to work too well.
1669 You have been warned!! */
1670 #if defined _MSC_VER && !defined WIN32
1671 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1672 The REALLOC define eliminates a flurry of conversion warnings,
1673 but is not required. */
1674 # define MAX_BUF_SIZE 65500L
1675 # define REALLOC(p,s) realloc ((p), (size_t) (s))
1677 # define MAX_BUF_SIZE (1L << 16)
1678 # define REALLOC(p,s) realloc ((p), (s))
1681 /* Extend the buffer by twice its current size via realloc and
1682 reset the pointers that pointed into the old block to point to the
1683 correct places in the new one. If extending the buffer results in it
1684 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1685 #define EXTEND_BUFFER() \
1687 unsigned char *old_buffer = bufp->buffer; \
1688 if (bufp->allocated == MAX_BUF_SIZE) \
1690 bufp->allocated <<= 1; \
1691 if (bufp->allocated > MAX_BUF_SIZE) \
1692 bufp->allocated = MAX_BUF_SIZE; \
1693 bufp->buffer = (unsigned char *) REALLOC (bufp->buffer, bufp->allocated);\
1694 if (bufp->buffer == NULL) \
1695 return REG_ESPACE; \
1696 /* If the buffer moved, move all the pointers into it. */ \
1697 if (old_buffer != bufp->buffer) \
1699 b = (b - old_buffer) + bufp->buffer; \
1700 begalt = (begalt - old_buffer) + bufp->buffer; \
1701 if (fixup_alt_jump) \
1702 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1704 laststart = (laststart - old_buffer) + bufp->buffer; \
1705 if (pending_exact) \
1706 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1711 /* Since we have one byte reserved for the register number argument to
1712 {start,stop}_memory, the maximum number of groups we can report
1713 things about is what fits in that byte. */
1714 #define MAX_REGNUM 255
1716 /* But patterns can have more than `MAX_REGNUM' registers. We just
1717 ignore the excess. */
1718 typedef unsigned regnum_t
;
1721 /* Macros for the compile stack. */
1723 /* Since offsets can go either forwards or backwards, this type needs to
1724 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1725 /* int may be not enough when sizeof(int) == 2. */
1726 typedef long pattern_offset_t
;
1730 pattern_offset_t begalt_offset
;
1731 pattern_offset_t fixup_alt_jump
;
1732 pattern_offset_t inner_group_offset
;
1733 pattern_offset_t laststart_offset
;
1735 } compile_stack_elt_t
;
1740 compile_stack_elt_t
*stack
;
1742 unsigned avail
; /* Offset of next open position. */
1743 } compile_stack_type
;
1746 #define INIT_COMPILE_STACK_SIZE 32
1748 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1749 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1751 /* The next available element. */
1752 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1755 /* Set the bit for character C in a list. */
1756 #define SET_LIST_BIT(c) \
1757 (b[((unsigned char) (c)) / BYTEWIDTH] \
1758 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1761 /* Get the next unsigned number in the uncompiled pattern. */
1762 #define GET_UNSIGNED_NUMBER(num) \
1766 while (ISDIGIT (c)) \
1770 num = num * 10 + c - '0'; \
1778 #if defined _LIBC || WIDE_CHAR_SUPPORT
1779 /* The GNU C library provides support for user-defined character classes
1780 and the functions from ISO C amendement 1. */
1781 # ifdef CHARCLASS_NAME_MAX
1782 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1784 /* This shouldn't happen but some implementation might still have this
1785 problem. Use a reasonable default value. */
1786 # define CHAR_CLASS_MAX_LENGTH 256
1790 # define IS_CHAR_CLASS(string) __wctype (string)
1792 # define IS_CHAR_CLASS(string) wctype (string)
1795 # define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1797 # define IS_CHAR_CLASS(string) \
1798 (STREQ (string, "alpha") || STREQ (string, "upper") \
1799 || STREQ (string, "lower") || STREQ (string, "digit") \
1800 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1801 || STREQ (string, "space") || STREQ (string, "print") \
1802 || STREQ (string, "punct") || STREQ (string, "graph") \
1803 || STREQ (string, "cntrl") || STREQ (string, "blank"))
1806 #ifndef MATCH_MAY_ALLOCATE
1808 /* If we cannot allocate large objects within re_match_2_internal,
1809 we make the fail stack and register vectors global.
1810 The fail stack, we grow to the maximum size when a regexp
1812 The register vectors, we adjust in size each time we
1813 compile a regexp, according to the number of registers it needs. */
1815 static fail_stack_type fail_stack
;
1817 /* Size with which the following vectors are currently allocated.
1818 That is so we can make them bigger as needed,
1819 but never make them smaller. */
1820 static int regs_allocated_size
;
1822 static const char ** regstart
, ** regend
;
1823 static const char ** old_regstart
, ** old_regend
;
1824 static const char **best_regstart
, **best_regend
;
1825 static register_info_type
*reg_info
;
1826 static const char **reg_dummy
;
1827 static register_info_type
*reg_info_dummy
;
1829 /* Make the register vectors big enough for NUM_REGS registers,
1830 but don't make them smaller. */
1833 regex_grow_registers (num_regs
)
1836 if (num_regs
> regs_allocated_size
)
1838 RETALLOC_IF (regstart
, num_regs
, const char *);
1839 RETALLOC_IF (regend
, num_regs
, const char *);
1840 RETALLOC_IF (old_regstart
, num_regs
, const char *);
1841 RETALLOC_IF (old_regend
, num_regs
, const char *);
1842 RETALLOC_IF (best_regstart
, num_regs
, const char *);
1843 RETALLOC_IF (best_regend
, num_regs
, const char *);
1844 RETALLOC_IF (reg_info
, num_regs
, register_info_type
);
1845 RETALLOC_IF (reg_dummy
, num_regs
, const char *);
1846 RETALLOC_IF (reg_info_dummy
, num_regs
, register_info_type
);
1848 regs_allocated_size
= num_regs
;
1852 #endif /* not MATCH_MAY_ALLOCATE */
1854 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
1858 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1859 Returns one of error codes defined in `regex.h', or zero for success.
1861 Assumes the `allocated' (and perhaps `buffer') and `translate'
1862 fields are set in BUFP on entry.
1864 If it succeeds, results are put in BUFP (if it returns an error, the
1865 contents of BUFP are undefined):
1866 `buffer' is the compiled pattern;
1867 `syntax' is set to SYNTAX;
1868 `used' is set to the length of the compiled pattern;
1869 `fastmap_accurate' is zero;
1870 `re_nsub' is the number of subexpressions in PATTERN;
1871 `not_bol' and `not_eol' are zero;
1873 The `fastmap' and `newline_anchor' fields are neither
1874 examined nor set. */
1876 /* Return, freeing storage we allocated. */
1877 #define FREE_STACK_RETURN(value) \
1878 return (free (compile_stack.stack), value)
1880 static reg_errcode_t
1881 regex_compile (pattern
, size
, syntax
, bufp
)
1882 const char *pattern
;
1884 reg_syntax_t syntax
;
1885 struct re_pattern_buffer
*bufp
;
1887 /* We fetch characters from PATTERN here. Even though PATTERN is
1888 `char *' (i.e., signed), we declare these variables as unsigned, so
1889 they can be reliably used as array indices. */
1890 register unsigned char c
, c1
;
1892 /* A random temporary spot in PATTERN. */
1895 /* Points to the end of the buffer, where we should append. */
1896 register unsigned char *b
;
1898 /* Keeps track of unclosed groups. */
1899 compile_stack_type compile_stack
;
1901 /* Points to the current (ending) position in the pattern. */
1902 const char *p
= pattern
;
1903 const char *pend
= pattern
+ size
;
1905 /* How to translate the characters in the pattern. */
1906 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
1908 /* Address of the count-byte of the most recently inserted `exactn'
1909 command. This makes it possible to tell if a new exact-match
1910 character can be added to that command or if the character requires
1911 a new `exactn' command. */
1912 unsigned char *pending_exact
= 0;
1914 /* Address of start of the most recently finished expression.
1915 This tells, e.g., postfix * where to find the start of its
1916 operand. Reset at the beginning of groups and alternatives. */
1917 unsigned char *laststart
= 0;
1919 /* Address of beginning of regexp, or inside of last group. */
1920 unsigned char *begalt
;
1922 /* Place in the uncompiled pattern (i.e., the {) to
1923 which to go back if the interval is invalid. */
1924 const char *beg_interval
;
1926 /* Address of the place where a forward jump should go to the end of
1927 the containing expression. Each alternative of an `or' -- except the
1928 last -- ends with a forward jump of this sort. */
1929 unsigned char *fixup_alt_jump
= 0;
1931 /* Counts open-groups as they are encountered. Remembered for the
1932 matching close-group on the compile stack, so the same register
1933 number is put in the stop_memory as the start_memory. */
1934 regnum_t regnum
= 0;
1937 DEBUG_PRINT1 ("\nCompiling pattern: ");
1940 unsigned debug_count
;
1942 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1943 putchar (pattern
[debug_count
]);
1948 /* Initialize the compile stack. */
1949 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1950 if (compile_stack
.stack
== NULL
)
1953 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
1954 compile_stack
.avail
= 0;
1956 /* Initialize the pattern buffer. */
1957 bufp
->syntax
= syntax
;
1958 bufp
->fastmap_accurate
= 0;
1959 bufp
->not_bol
= bufp
->not_eol
= 0;
1961 /* Set `used' to zero, so that if we return an error, the pattern
1962 printer (for debugging) will think there's no pattern. We reset it
1966 /* Always count groups, whether or not bufp->no_sub is set. */
1969 #if !defined emacs && !defined SYNTAX_TABLE
1970 /* Initialize the syntax table. */
1971 init_syntax_once ();
1974 if (bufp
->allocated
== 0)
1977 { /* If zero allocated, but buffer is non-null, try to realloc
1978 enough space. This loses if buffer's address is bogus, but
1979 that is the user's responsibility. */
1980 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
1983 { /* Caller did not allocate a buffer. Do it for them. */
1984 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
1986 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
1988 bufp
->allocated
= INIT_BUF_SIZE
;
1991 begalt
= b
= bufp
->buffer
;
1993 /* Loop through the uncompiled pattern until we're at the end. */
2002 if ( /* If at start of pattern, it's an operator. */
2004 /* If context independent, it's an operator. */
2005 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2006 /* Otherwise, depends on what's come before. */
2007 || at_begline_loc_p (pattern
, p
, syntax
))
2017 if ( /* If at end of pattern, it's an operator. */
2019 /* If context independent, it's an operator. */
2020 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2021 /* Otherwise, depends on what's next. */
2022 || at_endline_loc_p (p
, pend
, syntax
))
2032 if ((syntax
& RE_BK_PLUS_QM
)
2033 || (syntax
& RE_LIMITED_OPS
))
2037 /* If there is no previous pattern... */
2040 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2041 FREE_STACK_RETURN (REG_BADRPT
);
2042 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2047 /* Are we optimizing this jump? */
2048 boolean keep_string_p
= false;
2050 /* 1 means zero (many) matches is allowed. */
2051 char zero_times_ok
= 0, many_times_ok
= 0;
2053 /* If there is a sequence of repetition chars, collapse it
2054 down to just one (the right one). We can't combine
2055 interval operators with these because of, e.g., `a{2}*',
2056 which should only match an even number of `a's. */
2060 zero_times_ok
|= c
!= '+';
2061 many_times_ok
|= c
!= '?';
2069 || (!(syntax
& RE_BK_PLUS_QM
) && (c
== '+' || c
== '?')))
2072 else if (syntax
& RE_BK_PLUS_QM
&& c
== '\\')
2074 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2077 if (!(c1
== '+' || c1
== '?'))
2092 /* If we get here, we found another repeat character. */
2095 /* Star, etc. applied to an empty pattern is equivalent
2096 to an empty pattern. */
2100 /* Now we know whether or not zero matches is allowed
2101 and also whether or not two or more matches is allowed. */
2103 { /* More than one repetition is allowed, so put in at the
2104 end a backward relative jump from `b' to before the next
2105 jump we're going to put in below (which jumps from
2106 laststart to after this jump).
2108 But if we are at the `*' in the exact sequence `.*\n',
2109 insert an unconditional jump backwards to the .,
2110 instead of the beginning of the loop. This way we only
2111 push a failure point once, instead of every time
2112 through the loop. */
2113 assert (p
- 1 > pattern
);
2115 /* Allocate the space for the jump. */
2116 GET_BUFFER_SPACE (3);
2118 /* We know we are not at the first character of the pattern,
2119 because laststart was nonzero. And we've already
2120 incremented `p', by the way, to be the character after
2121 the `*'. Do we have to do something analogous here
2122 for null bytes, because of RE_DOT_NOT_NULL? */
2123 if (TRANSLATE (*(p
- 2)) == TRANSLATE ('.')
2125 && p
< pend
&& TRANSLATE (*p
) == TRANSLATE ('\n')
2126 && !(syntax
& RE_DOT_NEWLINE
))
2127 { /* We have .*\n. */
2128 STORE_JUMP (jump
, b
, laststart
);
2129 keep_string_p
= true;
2132 /* Anything else. */
2133 STORE_JUMP (maybe_pop_jump
, b
, laststart
- 3);
2135 /* We've added more stuff to the buffer. */
2139 /* On failure, jump from laststart to b + 3, which will be the
2140 end of the buffer after this jump is inserted. */
2141 GET_BUFFER_SPACE (3);
2142 INSERT_JUMP (keep_string_p
? on_failure_keep_string_jump
2150 /* At least one repetition is required, so insert a
2151 `dummy_failure_jump' before the initial
2152 `on_failure_jump' instruction of the loop. This
2153 effects a skip over that instruction the first time
2154 we hit that loop. */
2155 GET_BUFFER_SPACE (3);
2156 INSERT_JUMP (dummy_failure_jump
, laststart
, laststart
+ 6);
2171 boolean had_char_class
= false;
2173 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2175 /* Ensure that we have enough space to push a charset: the
2176 opcode, the length count, and the bitset; 34 bytes in all. */
2177 GET_BUFFER_SPACE (34);
2181 /* We test `*p == '^' twice, instead of using an if
2182 statement, so we only need one BUF_PUSH. */
2183 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2187 /* Remember the first position in the bracket expression. */
2190 /* Push the number of bytes in the bitmap. */
2191 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2193 /* Clear the whole map. */
2194 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2196 /* charset_not matches newline according to a syntax bit. */
2197 if ((re_opcode_t
) b
[-2] == charset_not
2198 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2199 SET_LIST_BIT ('\n');
2201 /* Read in characters and ranges, setting map bits. */
2204 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2208 /* \ might escape characters inside [...] and [^...]. */
2209 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2211 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2218 /* Could be the end of the bracket expression. If it's
2219 not (i.e., when the bracket expression is `[]' so
2220 far), the ']' character bit gets set way below. */
2221 if (c
== ']' && p
!= p1
+ 1)
2224 /* Look ahead to see if it's a range when the last thing
2225 was a character class. */
2226 if (had_char_class
&& c
== '-' && *p
!= ']')
2227 FREE_STACK_RETURN (REG_ERANGE
);
2229 /* Look ahead to see if it's a range when the last thing
2230 was a character: if this is a hyphen not at the
2231 beginning or the end of a list, then it's the range
2234 && !(p
- 2 >= pattern
&& p
[-2] == '[')
2235 && !(p
- 3 >= pattern
&& p
[-3] == '[' && p
[-2] == '^')
2239 = compile_range (&p
, pend
, translate
, syntax
, b
);
2240 if (ret
!= REG_NOERROR
) FREE_STACK_RETURN (ret
);
2243 else if (p
[0] == '-' && p
[1] != ']')
2244 { /* This handles ranges made up of characters only. */
2247 /* Move past the `-'. */
2250 ret
= compile_range (&p
, pend
, translate
, syntax
, b
);
2251 if (ret
!= REG_NOERROR
) FREE_STACK_RETURN (ret
);
2254 /* See if we're at the beginning of a possible character
2257 else if (syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2258 { /* Leave room for the null. */
2259 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2264 /* If pattern is `[[:'. */
2265 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2270 if ((c
== ':' && *p
== ']') || p
== pend
)
2272 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2275 /* This is in any case an invalid class name. */
2280 /* If isn't a word bracketed by `[:' and `:]':
2281 undo the ending character, the letters, and leave
2282 the leading `:' and `[' (but set bits for them). */
2283 if (c
== ':' && *p
== ']')
2285 #if defined _LIBC || WIDE_CHAR_SUPPORT
2286 boolean is_lower
= STREQ (str
, "lower");
2287 boolean is_upper
= STREQ (str
, "upper");
2291 wt
= IS_CHAR_CLASS (str
);
2293 FREE_STACK_RETURN (REG_ECTYPE
);
2295 /* Throw away the ] at the end of the character
2299 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2301 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ++ch
)
2304 if (__iswctype (__btowc (ch
), wt
))
2307 if (iswctype (btowc (ch
), wt
))
2311 if (translate
&& (is_upper
|| is_lower
)
2312 && (ISUPPER (ch
) || ISLOWER (ch
)))
2316 had_char_class
= true;
2319 boolean is_alnum
= STREQ (str
, "alnum");
2320 boolean is_alpha
= STREQ (str
, "alpha");
2321 boolean is_blank
= STREQ (str
, "blank");
2322 boolean is_cntrl
= STREQ (str
, "cntrl");
2323 boolean is_digit
= STREQ (str
, "digit");
2324 boolean is_graph
= STREQ (str
, "graph");
2325 boolean is_lower
= STREQ (str
, "lower");
2326 boolean is_print
= STREQ (str
, "print");
2327 boolean is_punct
= STREQ (str
, "punct");
2328 boolean is_space
= STREQ (str
, "space");
2329 boolean is_upper
= STREQ (str
, "upper");
2330 boolean is_xdigit
= STREQ (str
, "xdigit");
2332 if (!IS_CHAR_CLASS (str
))
2333 FREE_STACK_RETURN (REG_ECTYPE
);
2335 /* Throw away the ] at the end of the character
2339 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2341 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++)
2343 /* This was split into 3 if's to
2344 avoid an arbitrary limit in some compiler. */
2345 if ( (is_alnum
&& ISALNUM (ch
))
2346 || (is_alpha
&& ISALPHA (ch
))
2347 || (is_blank
&& ISBLANK (ch
))
2348 || (is_cntrl
&& ISCNTRL (ch
)))
2350 if ( (is_digit
&& ISDIGIT (ch
))
2351 || (is_graph
&& ISGRAPH (ch
))
2352 || (is_lower
&& ISLOWER (ch
))
2353 || (is_print
&& ISPRINT (ch
)))
2355 if ( (is_punct
&& ISPUNCT (ch
))
2356 || (is_space
&& ISSPACE (ch
))
2357 || (is_upper
&& ISUPPER (ch
))
2358 || (is_xdigit
&& ISXDIGIT (ch
)))
2360 if ( translate
&& (is_upper
|| is_lower
)
2361 && (ISUPPER (ch
) || ISLOWER (ch
)))
2364 had_char_class
= true;
2365 #endif /* libc || wctype.h */
2374 had_char_class
= false;
2379 had_char_class
= false;
2384 /* Discard any (non)matching list bytes that are all 0 at the
2385 end of the map. Decrease the map-length byte too. */
2386 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2394 if (syntax
& RE_NO_BK_PARENS
)
2401 if (syntax
& RE_NO_BK_PARENS
)
2408 if (syntax
& RE_NEWLINE_ALT
)
2415 if (syntax
& RE_NO_BK_VBAR
)
2422 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2423 goto handle_interval
;
2429 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2431 /* Do not translate the character after the \, so that we can
2432 distinguish, e.g., \B from \b, even if we normally would
2433 translate, e.g., B to b. */
2439 if (syntax
& RE_NO_BK_PARENS
)
2440 goto normal_backslash
;
2446 if (COMPILE_STACK_FULL
)
2448 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2449 compile_stack_elt_t
);
2450 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2452 compile_stack
.size
<<= 1;
2455 /* These are the values to restore when we hit end of this
2456 group. They are all relative offsets, so that if the
2457 whole pattern moves because of realloc, they will still
2459 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2460 COMPILE_STACK_TOP
.fixup_alt_jump
2461 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2462 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2463 COMPILE_STACK_TOP
.regnum
= regnum
;
2465 /* We will eventually replace the 0 with the number of
2466 groups inner to this one. But do not push a
2467 start_memory for groups beyond the last one we can
2468 represent in the compiled pattern. */
2469 if (regnum
<= MAX_REGNUM
)
2471 COMPILE_STACK_TOP
.inner_group_offset
= b
- bufp
->buffer
+ 2;
2472 BUF_PUSH_3 (start_memory
, regnum
, 0);
2475 compile_stack
.avail
++;
2480 /* If we've reached MAX_REGNUM groups, then this open
2481 won't actually generate any code, so we'll have to
2482 clear pending_exact explicitly. */
2488 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2490 if (COMPILE_STACK_EMPTY
)
2492 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2493 goto normal_backslash
;
2495 FREE_STACK_RETURN (REG_ERPAREN
);
2500 { /* Push a dummy failure point at the end of the
2501 alternative for a possible future
2502 `pop_failure_jump' to pop. See comments at
2503 `push_dummy_failure' in `re_match_2'. */
2504 BUF_PUSH (push_dummy_failure
);
2506 /* We allocated space for this jump when we assigned
2507 to `fixup_alt_jump', in the `handle_alt' case below. */
2508 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
- 1);
2511 /* See similar code for backslashed left paren above. */
2512 if (COMPILE_STACK_EMPTY
)
2514 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2517 FREE_STACK_RETURN (REG_ERPAREN
);
2520 /* Since we just checked for an empty stack above, this
2521 ``can't happen''. */
2522 assert (compile_stack
.avail
!= 0);
2524 /* We don't just want to restore into `regnum', because
2525 later groups should continue to be numbered higher,
2526 as in `(ab)c(de)' -- the second group is #2. */
2527 regnum_t this_group_regnum
;
2529 compile_stack
.avail
--;
2530 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2532 = COMPILE_STACK_TOP
.fixup_alt_jump
2533 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2535 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2536 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2537 /* If we've reached MAX_REGNUM groups, then this open
2538 won't actually generate any code, so we'll have to
2539 clear pending_exact explicitly. */
2542 /* We're at the end of the group, so now we know how many
2543 groups were inside this one. */
2544 if (this_group_regnum
<= MAX_REGNUM
)
2546 unsigned char *inner_group_loc
2547 = bufp
->buffer
+ COMPILE_STACK_TOP
.inner_group_offset
;
2549 *inner_group_loc
= regnum
- this_group_regnum
;
2550 BUF_PUSH_3 (stop_memory
, this_group_regnum
,
2551 regnum
- this_group_regnum
);
2557 case '|': /* `\|'. */
2558 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2559 goto normal_backslash
;
2561 if (syntax
& RE_LIMITED_OPS
)
2564 /* Insert before the previous alternative a jump which
2565 jumps to this alternative if the former fails. */
2566 GET_BUFFER_SPACE (3);
2567 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2571 /* The alternative before this one has a jump after it
2572 which gets executed if it gets matched. Adjust that
2573 jump so it will jump to this alternative's analogous
2574 jump (put in below, which in turn will jump to the next
2575 (if any) alternative's such jump, etc.). The last such
2576 jump jumps to the correct final destination. A picture:
2582 If we are at `b', then fixup_alt_jump right now points to a
2583 three-byte space after `a'. We'll put in the jump, set
2584 fixup_alt_jump to right after `b', and leave behind three
2585 bytes which we'll fill in when we get to after `c'. */
2588 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
);
2590 /* Mark and leave space for a jump after this alternative,
2591 to be filled in later either by next alternative or
2592 when know we're at the end of a series of alternatives. */
2594 GET_BUFFER_SPACE (3);
2603 /* If \{ is a literal. */
2604 if (!(syntax
& RE_INTERVALS
)
2605 /* If we're at `\{' and it's not the open-interval
2607 || ((syntax
& RE_INTERVALS
) && (syntax
& RE_NO_BK_BRACES
))
2608 || (p
- 2 == pattern
&& p
== pend
))
2609 goto normal_backslash
;
2613 /* If got here, then the syntax allows intervals. */
2615 /* At least (most) this many matches must be made. */
2616 int lower_bound
= -1, upper_bound
= -1;
2618 beg_interval
= p
- 1;
2622 if (syntax
& RE_NO_BK_BRACES
)
2623 goto unfetch_interval
;
2625 FREE_STACK_RETURN (REG_EBRACE
);
2628 GET_UNSIGNED_NUMBER (lower_bound
);
2632 GET_UNSIGNED_NUMBER (upper_bound
);
2633 if (upper_bound
< 0) upper_bound
= RE_DUP_MAX
;
2636 /* Interval such as `{1}' => match exactly once. */
2637 upper_bound
= lower_bound
;
2639 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2640 || lower_bound
> upper_bound
)
2642 if (syntax
& RE_NO_BK_BRACES
)
2643 goto unfetch_interval
;
2645 FREE_STACK_RETURN (REG_BADBR
);
2648 if (!(syntax
& RE_NO_BK_BRACES
))
2650 if (c
!= '\\') FREE_STACK_RETURN (REG_EBRACE
);
2657 if (syntax
& RE_NO_BK_BRACES
)
2658 goto unfetch_interval
;
2660 FREE_STACK_RETURN (REG_BADBR
);
2663 /* We just parsed a valid interval. */
2665 /* If it's invalid to have no preceding re. */
2668 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2669 FREE_STACK_RETURN (REG_BADRPT
);
2670 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2673 goto unfetch_interval
;
2676 /* If the upper bound is zero, don't want to succeed at
2677 all; jump from `laststart' to `b + 3', which will be
2678 the end of the buffer after we insert the jump. */
2679 if (upper_bound
== 0)
2681 GET_BUFFER_SPACE (3);
2682 INSERT_JUMP (jump
, laststart
, b
+ 3);
2686 /* Otherwise, we have a nontrivial interval. When
2687 we're all done, the pattern will look like:
2688 set_number_at <jump count> <upper bound>
2689 set_number_at <succeed_n count> <lower bound>
2690 succeed_n <after jump addr> <succeed_n count>
2692 jump_n <succeed_n addr> <jump count>
2693 (The upper bound and `jump_n' are omitted if
2694 `upper_bound' is 1, though.) */
2696 { /* If the upper bound is > 1, we need to insert
2697 more at the end of the loop. */
2698 unsigned nbytes
= 10 + (upper_bound
> 1) * 10;
2700 GET_BUFFER_SPACE (nbytes
);
2702 /* Initialize lower bound of the `succeed_n', even
2703 though it will be set during matching by its
2704 attendant `set_number_at' (inserted next),
2705 because `re_compile_fastmap' needs to know.
2706 Jump to the `jump_n' we might insert below. */
2707 INSERT_JUMP2 (succeed_n
, laststart
,
2708 b
+ 5 + (upper_bound
> 1) * 5,
2712 /* Code to initialize the lower bound. Insert
2713 before the `succeed_n'. The `5' is the last two
2714 bytes of this `set_number_at', plus 3 bytes of
2715 the following `succeed_n'. */
2716 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
2719 if (upper_bound
> 1)
2720 { /* More than one repetition is allowed, so
2721 append a backward jump to the `succeed_n'
2722 that starts this interval.
2724 When we've reached this during matching,
2725 we'll have matched the interval once, so
2726 jump back only `upper_bound - 1' times. */
2727 STORE_JUMP2 (jump_n
, b
, laststart
+ 5,
2731 /* The location we want to set is the second
2732 parameter of the `jump_n'; that is `b-2' as
2733 an absolute address. `laststart' will be
2734 the `set_number_at' we're about to insert;
2735 `laststart+3' the number to set, the source
2736 for the relative address. But we are
2737 inserting into the middle of the pattern --
2738 so everything is getting moved up by 5.
2739 Conclusion: (b - 2) - (laststart + 3) + 5,
2740 i.e., b - laststart.
2742 We insert this at the beginning of the loop
2743 so that if we fail during matching, we'll
2744 reinitialize the bounds. */
2745 insert_op2 (set_number_at
, laststart
, b
- laststart
,
2746 upper_bound
- 1, b
);
2751 beg_interval
= NULL
;
2756 /* If an invalid interval, match the characters as literals. */
2757 assert (beg_interval
);
2759 beg_interval
= NULL
;
2761 /* normal_char and normal_backslash need `c'. */
2764 if (!(syntax
& RE_NO_BK_BRACES
))
2766 if (p
> pattern
&& p
[-1] == '\\')
2767 goto normal_backslash
;
2772 /* There is no way to specify the before_dot and after_dot
2773 operators. rms says this is ok. --karl */
2781 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2787 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
2793 if (syntax
& RE_NO_GNU_OPS
)
2796 BUF_PUSH (wordchar
);
2801 if (syntax
& RE_NO_GNU_OPS
)
2804 BUF_PUSH (notwordchar
);
2809 if (syntax
& RE_NO_GNU_OPS
)
2815 if (syntax
& RE_NO_GNU_OPS
)
2821 if (syntax
& RE_NO_GNU_OPS
)
2823 BUF_PUSH (wordbound
);
2827 if (syntax
& RE_NO_GNU_OPS
)
2829 BUF_PUSH (notwordbound
);
2833 if (syntax
& RE_NO_GNU_OPS
)
2839 if (syntax
& RE_NO_GNU_OPS
)
2844 case '1': case '2': case '3': case '4': case '5':
2845 case '6': case '7': case '8': case '9':
2846 if (syntax
& RE_NO_BK_REFS
)
2852 FREE_STACK_RETURN (REG_ESUBREG
);
2854 /* Can't back reference to a subexpression if inside of it. */
2855 if (group_in_compile_stack (compile_stack
, (regnum_t
) c1
))
2859 BUF_PUSH_2 (duplicate
, c1
);
2865 if (syntax
& RE_BK_PLUS_QM
)
2868 goto normal_backslash
;
2872 /* You might think it would be useful for \ to mean
2873 not to translate; but if we don't translate it
2874 it will never match anything. */
2882 /* Expects the character in `c'. */
2884 /* If no exactn currently being built. */
2887 /* If last exactn not at current position. */
2888 || pending_exact
+ *pending_exact
+ 1 != b
2890 /* We have only one byte following the exactn for the count. */
2891 || *pending_exact
== (1 << BYTEWIDTH
) - 1
2893 /* If followed by a repetition operator. */
2894 || *p
== '*' || *p
== '^'
2895 || ((syntax
& RE_BK_PLUS_QM
)
2896 ? *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
2897 : (*p
== '+' || *p
== '?'))
2898 || ((syntax
& RE_INTERVALS
)
2899 && ((syntax
& RE_NO_BK_BRACES
)
2901 : (p
[0] == '\\' && p
[1] == '{'))))
2903 /* Start building a new exactn. */
2907 BUF_PUSH_2 (exactn
, 0);
2908 pending_exact
= b
- 1;
2915 } /* while p != pend */
2918 /* Through the pattern now. */
2921 STORE_JUMP (jump_past_alt
, fixup_alt_jump
, b
);
2923 if (!COMPILE_STACK_EMPTY
)
2924 FREE_STACK_RETURN (REG_EPAREN
);
2926 /* If we don't want backtracking, force success
2927 the first time we reach the end of the compiled pattern. */
2928 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
2931 free (compile_stack
.stack
);
2933 /* We have succeeded; set the length of the buffer. */
2934 bufp
->used
= b
- bufp
->buffer
;
2939 DEBUG_PRINT1 ("\nCompiled pattern: \n");
2940 print_compiled_pattern (bufp
);
2944 #ifndef MATCH_MAY_ALLOCATE
2945 /* Initialize the failure stack to the largest possible stack. This
2946 isn't necessary unless we're trying to avoid calling alloca in
2947 the search and match routines. */
2949 int num_regs
= bufp
->re_nsub
+ 1;
2951 /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2952 is strictly greater than re_max_failures, the largest possible stack
2953 is 2 * re_max_failures failure points. */
2954 if (fail_stack
.size
< (2 * re_max_failures
* MAX_FAILURE_ITEMS
))
2956 fail_stack
.size
= (2 * re_max_failures
* MAX_FAILURE_ITEMS
);
2959 if (! fail_stack
.stack
)
2961 = (fail_stack_elt_t
*) xmalloc (fail_stack
.size
2962 * sizeof (fail_stack_elt_t
));
2965 = (fail_stack_elt_t
*) xrealloc (fail_stack
.stack
,
2967 * sizeof (fail_stack_elt_t
)));
2968 # else /* not emacs */
2969 if (! fail_stack
.stack
)
2971 = (fail_stack_elt_t
*) malloc (fail_stack
.size
2972 * sizeof (fail_stack_elt_t
));
2975 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
2977 * sizeof (fail_stack_elt_t
)));
2978 # endif /* not emacs */
2981 regex_grow_registers (num_regs
);
2983 #endif /* not MATCH_MAY_ALLOCATE */
2986 } /* regex_compile */
2988 /* Subroutines for `regex_compile'. */
2990 /* Store OP at LOC followed by two-byte integer parameter ARG. */
2993 store_op1 (op
, loc
, arg
)
2998 *loc
= (unsigned char) op
;
2999 STORE_NUMBER (loc
+ 1, arg
);
3003 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3006 store_op2 (op
, loc
, arg1
, arg2
)
3011 *loc
= (unsigned char) op
;
3012 STORE_NUMBER (loc
+ 1, arg1
);
3013 STORE_NUMBER (loc
+ 3, arg2
);
3017 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3018 for OP followed by two-byte integer parameter ARG. */
3021 insert_op1 (op
, loc
, arg
, end
)
3027 register unsigned char *pfrom
= end
;
3028 register unsigned char *pto
= end
+ 3;
3030 while (pfrom
!= loc
)
3033 store_op1 (op
, loc
, arg
);
3037 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3040 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3046 register unsigned char *pfrom
= end
;
3047 register unsigned char *pto
= end
+ 5;
3049 while (pfrom
!= loc
)
3052 store_op2 (op
, loc
, arg1
, arg2
);
3056 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3057 after an alternative or a begin-subexpression. We assume there is at
3058 least one character before the ^. */
3061 at_begline_loc_p (pattern
, p
, syntax
)
3062 const char *pattern
, *p
;
3063 reg_syntax_t syntax
;
3065 const char *prev
= p
- 2;
3066 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3069 /* After a subexpression? */
3070 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3071 /* After an alternative? */
3072 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
));
3076 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3077 at least one character after the $, i.e., `P < PEND'. */
3080 at_endline_loc_p (p
, pend
, syntax
)
3081 const char *p
, *pend
;
3082 reg_syntax_t syntax
;
3084 const char *next
= p
;
3085 boolean next_backslash
= *next
== '\\';
3086 const char *next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3089 /* Before a subexpression? */
3090 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3091 : next_backslash
&& next_next
&& *next_next
== ')')
3092 /* Before an alternative? */
3093 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3094 : next_backslash
&& next_next
&& *next_next
== '|');
3098 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3099 false if it's not. */
3102 group_in_compile_stack (compile_stack
, regnum
)
3103 compile_stack_type compile_stack
;
3108 for (this_element
= compile_stack
.avail
- 1;
3111 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3118 /* Read the ending character of a range (in a bracket expression) from the
3119 uncompiled pattern *P_PTR (which ends at PEND). We assume the
3120 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
3121 Then we set the translation of all bits between the starting and
3122 ending characters (inclusive) in the compiled pattern B.
3124 Return an error code.
3126 We use these short variable names so we can use the same macros as
3127 `regex_compile' itself. */
3129 static reg_errcode_t
3130 compile_range (p_ptr
, pend
, translate
, syntax
, b
)
3131 const char **p_ptr
, *pend
;
3132 RE_TRANSLATE_TYPE translate
;
3133 reg_syntax_t syntax
;
3138 const char *p
= *p_ptr
;
3139 unsigned int range_start
, range_end
;
3144 /* Even though the pattern is a signed `char *', we need to fetch
3145 with unsigned char *'s; if the high bit of the pattern character
3146 is set, the range endpoints will be negative if we fetch using a
3149 We also want to fetch the endpoints without translating them; the
3150 appropriate translation is done in the bit-setting loop below. */
3151 /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */
3152 range_start
= ((const unsigned char *) p
)[-2];
3153 range_end
= ((const unsigned char *) p
)[0];
3155 /* Have to increment the pointer into the pattern string, so the
3156 caller isn't still at the ending character. */
3159 /* If the start is after the end, the range is empty. */
3160 if (range_start
> range_end
)
3161 return syntax
& RE_NO_EMPTY_RANGES
? REG_ERANGE
: REG_NOERROR
;
3163 /* Here we see why `this_char' has to be larger than an `unsigned
3164 char' -- the range is inclusive, so if `range_end' == 0xff
3165 (assuming 8-bit characters), we would otherwise go into an infinite
3166 loop, since all characters <= 0xff. */
3167 for (this_char
= range_start
; this_char
<= range_end
; this_char
++)
3169 SET_LIST_BIT (TRANSLATE (this_char
));
3175 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3176 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3177 characters can start a string that matches the pattern. This fastmap
3178 is used by re_search to skip quickly over impossible starting points.
3180 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3181 area as BUFP->fastmap.
3183 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3186 Returns 0 if we succeed, -2 if an internal error. */
3189 re_compile_fastmap (bufp
)
3190 struct re_pattern_buffer
*bufp
;
3193 #ifdef MATCH_MAY_ALLOCATE
3194 fail_stack_type fail_stack
;
3196 #ifndef REGEX_MALLOC
3200 register char *fastmap
= bufp
->fastmap
;
3201 unsigned char *pattern
= bufp
->buffer
;
3202 unsigned char *p
= pattern
;
3203 register unsigned char *pend
= pattern
+ bufp
->used
;
3206 /* This holds the pointer to the failure stack, when
3207 it is allocated relocatably. */
3208 fail_stack_elt_t
*failure_stack_ptr
;
3211 /* Assume that each path through the pattern can be null until
3212 proven otherwise. We set this false at the bottom of switch
3213 statement, to which we get only if a particular path doesn't
3214 match the empty string. */
3215 boolean path_can_be_null
= true;
3217 /* We aren't doing a `succeed_n' to begin with. */
3218 boolean succeed_n_p
= false;
3220 assert (fastmap
!= NULL
&& p
!= NULL
);
3223 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3224 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3225 bufp
->can_be_null
= 0;
3229 if (p
== pend
|| *p
== succeed
)
3231 /* We have reached the (effective) end of pattern. */
3232 if (!FAIL_STACK_EMPTY ())
3234 bufp
->can_be_null
|= path_can_be_null
;
3236 /* Reset for next path. */
3237 path_can_be_null
= true;
3239 p
= fail_stack
.stack
[--fail_stack
.avail
].pointer
;
3247 /* We should never be about to go beyond the end of the pattern. */
3250 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3253 /* I guess the idea here is to simply not bother with a fastmap
3254 if a backreference is used, since it's too hard to figure out
3255 the fastmap for the corresponding group. Setting
3256 `can_be_null' stops `re_search_2' from using the fastmap, so
3257 that is all we do. */
3259 bufp
->can_be_null
= 1;
3263 /* Following are the cases which match a character. These end
3272 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
3273 if (p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
)))
3279 /* Chars beyond end of map must be allowed. */
3280 for (j
= *p
* BYTEWIDTH
; j
< (1 << BYTEWIDTH
); j
++)
3283 for (j
= *p
++ * BYTEWIDTH
- 1; j
>= 0; j
--)
3284 if (!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))))
3290 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3291 if (SYNTAX (j
) == Sword
)
3297 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3298 if (SYNTAX (j
) != Sword
)
3305 int fastmap_newline
= fastmap
['\n'];
3307 /* `.' matches anything ... */
3308 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3311 /* ... except perhaps newline. */
3312 if (!(bufp
->syntax
& RE_DOT_NEWLINE
))
3313 fastmap
['\n'] = fastmap_newline
;
3315 /* Return if we have already set `can_be_null'; if we have,
3316 then the fastmap is irrelevant. Something's wrong here. */
3317 else if (bufp
->can_be_null
)
3320 /* Otherwise, have to check alternative paths. */
3327 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3328 if (SYNTAX (j
) == (enum syntaxcode
) k
)
3335 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3336 if (SYNTAX (j
) != (enum syntaxcode
) k
)
3341 /* All cases after this match the empty string. These end with
3361 case push_dummy_failure
:
3366 case pop_failure_jump
:
3367 case maybe_pop_jump
:
3370 case dummy_failure_jump
:
3371 EXTRACT_NUMBER_AND_INCR (j
, p
);
3376 /* Jump backward implies we just went through the body of a
3377 loop and matched nothing. Opcode jumped to should be
3378 `on_failure_jump' or `succeed_n'. Just treat it like an
3379 ordinary jump. For a * loop, it has pushed its failure
3380 point already; if so, discard that as redundant. */
3381 if ((re_opcode_t
) *p
!= on_failure_jump
3382 && (re_opcode_t
) *p
!= succeed_n
)
3386 EXTRACT_NUMBER_AND_INCR (j
, p
);
3389 /* If what's on the stack is where we are now, pop it. */
3390 if (!FAIL_STACK_EMPTY ()
3391 && fail_stack
.stack
[fail_stack
.avail
- 1].pointer
== p
)
3397 case on_failure_jump
:
3398 case on_failure_keep_string_jump
:
3399 handle_on_failure_jump
:
3400 EXTRACT_NUMBER_AND_INCR (j
, p
);
3402 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3403 end of the pattern. We don't want to push such a point,
3404 since when we restore it above, entering the switch will
3405 increment `p' past the end of the pattern. We don't need
3406 to push such a point since we obviously won't find any more
3407 fastmap entries beyond `pend'. Such a pattern can match
3408 the null string, though. */
3411 if (!PUSH_PATTERN_OP (p
+ j
, fail_stack
))
3413 RESET_FAIL_STACK ();
3418 bufp
->can_be_null
= 1;
3422 EXTRACT_NUMBER_AND_INCR (k
, p
); /* Skip the n. */
3423 succeed_n_p
= false;
3430 /* Get to the number of times to succeed. */
3433 /* Increment p past the n for when k != 0. */
3434 EXTRACT_NUMBER_AND_INCR (k
, p
);
3438 succeed_n_p
= true; /* Spaghetti code alert. */
3439 goto handle_on_failure_jump
;
3456 abort (); /* We have listed all the cases. */
3459 /* Getting here means we have found the possible starting
3460 characters for one path of the pattern -- and that the empty
3461 string does not match. We need not follow this path further.
3462 Instead, look at the next alternative (remembered on the
3463 stack), or quit if no more. The test at the top of the loop
3464 does these things. */
3465 path_can_be_null
= false;
3469 /* Set `can_be_null' for the last path (also the first path, if the
3470 pattern is empty). */
3471 bufp
->can_be_null
|= path_can_be_null
;
3474 RESET_FAIL_STACK ();
3476 } /* re_compile_fastmap */
3478 weak_alias (__re_compile_fastmap
, re_compile_fastmap
)
3481 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3482 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3483 this memory for recording register information. STARTS and ENDS
3484 must be allocated using the malloc library routine, and must each
3485 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3487 If NUM_REGS == 0, then subsequent matches should allocate their own
3490 Unless this function is called, the first search or match using
3491 PATTERN_BUFFER will allocate its own register data, without
3492 freeing the old data. */
3495 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3496 struct re_pattern_buffer
*bufp
;
3497 struct re_registers
*regs
;
3499 regoff_t
*starts
, *ends
;
3503 bufp
->regs_allocated
= REGS_REALLOCATE
;
3504 regs
->num_regs
= num_regs
;
3505 regs
->start
= starts
;
3510 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3512 regs
->start
= regs
->end
= (regoff_t
*) 0;
3516 weak_alias (__re_set_registers
, re_set_registers
)
3519 /* Searching routines. */
3521 /* Like re_search_2, below, but only one string is specified, and
3522 doesn't let you say where to stop matching. */
3525 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3526 struct re_pattern_buffer
*bufp
;
3528 int size
, startpos
, range
;
3529 struct re_registers
*regs
;
3531 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3535 weak_alias (__re_search
, re_search
)
3539 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3540 virtual concatenation of STRING1 and STRING2, starting first at index
3541 STARTPOS, then at STARTPOS + 1, and so on.
3543 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3545 RANGE is how far to scan while trying to match. RANGE = 0 means try
3546 only at STARTPOS; in general, the last start tried is STARTPOS +
3549 In REGS, return the indices of the virtual concatenation of STRING1
3550 and STRING2 that matched the entire BUFP->buffer and its contained
3553 Do not consider matching one past the index STOP in the virtual
3554 concatenation of STRING1 and STRING2.
3556 We return either the position in the strings at which the match was
3557 found, -1 if no match, or -2 if error (such as failure
3561 re_search_2 (bufp
, string1
, size1
, string2
, size2
, startpos
, range
, regs
, stop
)
3562 struct re_pattern_buffer
*bufp
;
3563 const char *string1
, *string2
;
3567 struct re_registers
*regs
;
3571 register char *fastmap
= bufp
->fastmap
;
3572 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3573 int total_size
= size1
+ size2
;
3574 int endpos
= startpos
+ range
;
3576 /* Check for out-of-range STARTPOS. */
3577 if (startpos
< 0 || startpos
> total_size
)
3580 /* Fix up RANGE if it might eventually take us outside
3581 the virtual concatenation of STRING1 and STRING2.
3582 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3584 range
= 0 - startpos
;
3585 else if (endpos
> total_size
)
3586 range
= total_size
- startpos
;
3588 /* If the search isn't to be a backwards one, don't waste time in a
3589 search for a pattern that must be anchored. */
3590 if (bufp
->used
> 0 && range
> 0
3591 && ((re_opcode_t
) bufp
->buffer
[0] == begbuf
3592 /* `begline' is like `begbuf' if it cannot match at newlines. */
3593 || ((re_opcode_t
) bufp
->buffer
[0] == begline
3594 && !bufp
->newline_anchor
)))
3603 /* In a forward search for something that starts with \=.
3604 don't keep searching past point. */
3605 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3607 range
= PT
- startpos
;
3613 /* Update the fastmap now if not correct already. */
3614 if (fastmap
&& !bufp
->fastmap_accurate
)
3615 if (re_compile_fastmap (bufp
) == -2)
3618 /* Loop through the string, looking for a place to start matching. */
3621 /* If a fastmap is supplied, skip quickly over characters that
3622 cannot be the start of a match. If the pattern can match the
3623 null string, however, we don't need to skip characters; we want
3624 the first null string. */
3625 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3627 if (range
> 0) /* Searching forwards. */
3629 register const char *d
;
3630 register int lim
= 0;
3633 if (startpos
< size1
&& startpos
+ range
>= size1
)
3634 lim
= range
- (size1
- startpos
);
3636 d
= (startpos
>= size1
? string2
- size1
: string1
) + startpos
;
3638 /* Written out as an if-else to avoid testing `translate'
3642 && !fastmap
[(unsigned char)
3643 translate
[(unsigned char) *d
++]])
3646 while (range
> lim
&& !fastmap
[(unsigned char) *d
++])
3649 startpos
+= irange
- range
;
3651 else /* Searching backwards. */
3653 register char c
= (size1
== 0 || startpos
>= size1
3654 ? string2
[startpos
- size1
]
3655 : string1
[startpos
]);
3657 if (!fastmap
[(unsigned char) TRANSLATE (c
)])
3662 /* If can't match the null string, and that's all we have left, fail. */
3663 if (range
>= 0 && startpos
== total_size
&& fastmap
3664 && !bufp
->can_be_null
)
3667 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3668 startpos
, regs
, stop
);
3669 #ifndef REGEX_MALLOC
3698 weak_alias (__re_search_2
, re_search_2
)
3701 /* This converts PTR, a pointer into one of the search strings `string1'
3702 and `string2' into an offset from the beginning of that string. */
3703 #define POINTER_TO_OFFSET(ptr) \
3704 (FIRST_STRING_P (ptr) \
3705 ? ((regoff_t) ((ptr) - string1)) \
3706 : ((regoff_t) ((ptr) - string2 + size1)))
3708 /* Macros for dealing with the split strings in re_match_2. */
3710 #define MATCHING_IN_FIRST_STRING (dend == end_match_1)
3712 /* Call before fetching a character with *d. This switches over to
3713 string2 if necessary. */
3714 #define PREFETCH() \
3717 /* End of string2 => fail. */ \
3718 if (dend == end_match_2) \
3720 /* End of string1 => advance to string2. */ \
3722 dend = end_match_2; \
3726 /* Test if at very beginning or at very end of the virtual concatenation
3727 of `string1' and `string2'. If only one string, it's `string2'. */
3728 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3729 #define AT_STRINGS_END(d) ((d) == end2)
3732 /* Test if D points to a character which is word-constituent. We have
3733 two special cases to check for: if past the end of string1, look at
3734 the first character in string2; and if before the beginning of
3735 string2, look at the last character in string1. */
3736 #define WORDCHAR_P(d) \
3737 (SYNTAX ((d) == end1 ? *string2 \
3738 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3741 /* Disabled due to a compiler bug -- see comment at case wordbound */
3743 /* Test if the character before D and the one at D differ with respect
3744 to being word-constituent. */
3745 #define AT_WORD_BOUNDARY(d) \
3746 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3747 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3750 /* Free everything we malloc. */
3751 #ifdef MATCH_MAY_ALLOCATE
3752 # define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3753 # define FREE_VARIABLES() \
3755 REGEX_FREE_STACK (fail_stack.stack); \
3756 FREE_VAR (regstart); \
3757 FREE_VAR (regend); \
3758 FREE_VAR (old_regstart); \
3759 FREE_VAR (old_regend); \
3760 FREE_VAR (best_regstart); \
3761 FREE_VAR (best_regend); \
3762 FREE_VAR (reg_info); \
3763 FREE_VAR (reg_dummy); \
3764 FREE_VAR (reg_info_dummy); \
3767 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
3768 #endif /* not MATCH_MAY_ALLOCATE */
3770 /* These values must meet several constraints. They must not be valid
3771 register values; since we have a limit of 255 registers (because
3772 we use only one byte in the pattern for the register number), we can
3773 use numbers larger than 255. They must differ by 1, because of
3774 NUM_FAILURE_ITEMS above. And the value for the lowest register must
3775 be larger than the value for the highest register, so we do not try
3776 to actually save any registers when none are active. */
3777 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3778 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3780 /* Matching routines. */
3782 #ifndef emacs /* Emacs never uses this. */
3783 /* re_match is like re_match_2 except it takes only a single string. */
3786 re_match (bufp
, string
, size
, pos
, regs
)
3787 struct re_pattern_buffer
*bufp
;
3790 struct re_registers
*regs
;
3792 int result
= re_match_2_internal (bufp
, NULL
, 0, string
, size
,
3794 # ifndef REGEX_MALLOC
3802 weak_alias (__re_match
, re_match
)
3804 #endif /* not emacs */
3806 static boolean group_match_null_string_p
_RE_ARGS ((unsigned char **p
,
3808 register_info_type
*reg_info
));
3809 static boolean alt_match_null_string_p
_RE_ARGS ((unsigned char *p
,
3811 register_info_type
*reg_info
));
3812 static boolean common_op_match_null_string_p
_RE_ARGS ((unsigned char **p
,
3814 register_info_type
*reg_info
));
3815 static int bcmp_translate
_RE_ARGS ((const char *s1
, const char *s2
,
3816 int len
, char *translate
));
3818 /* re_match_2 matches the compiled pattern in BUFP against the
3819 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3820 and SIZE2, respectively). We start matching at POS, and stop
3823 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3824 store offsets for the substring each group matched in REGS. See the
3825 documentation for exactly how many groups we fill.
3827 We return -1 if no match, -2 if an internal error (such as the
3828 failure stack overflowing). Otherwise, we return the length of the
3829 matched substring. */
3832 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
3833 struct re_pattern_buffer
*bufp
;
3834 const char *string1
, *string2
;
3837 struct re_registers
*regs
;
3840 int result
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3842 #ifndef REGEX_MALLOC
3850 weak_alias (__re_match_2
, re_match_2
)
3853 /* This is a separate function so that we can force an alloca cleanup
3856 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
3857 struct re_pattern_buffer
*bufp
;
3858 const char *string1
, *string2
;
3861 struct re_registers
*regs
;
3864 /* General temporaries. */
3868 /* Just past the end of the corresponding string. */
3869 const char *end1
, *end2
;
3871 /* Pointers into string1 and string2, just past the last characters in
3872 each to consider matching. */
3873 const char *end_match_1
, *end_match_2
;
3875 /* Where we are in the data, and the end of the current string. */
3876 const char *d
, *dend
;
3878 /* Where we are in the pattern, and the end of the pattern. */
3879 unsigned char *p
= bufp
->buffer
;
3880 register unsigned char *pend
= p
+ bufp
->used
;
3882 /* Mark the opcode just after a start_memory, so we can test for an
3883 empty subpattern when we get to the stop_memory. */
3884 unsigned char *just_past_start_mem
= 0;
3886 /* We use this to map every character in the string. */
3887 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3889 /* Failure point stack. Each place that can handle a failure further
3890 down the line pushes a failure point on this stack. It consists of
3891 restart, regend, and reg_info for all registers corresponding to
3892 the subexpressions we're currently inside, plus the number of such
3893 registers, and, finally, two char *'s. The first char * is where
3894 to resume scanning the pattern; the second one is where to resume
3895 scanning the strings. If the latter is zero, the failure point is
3896 a ``dummy''; if a failure happens and the failure point is a dummy,
3897 it gets discarded and the next next one is tried. */
3898 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3899 fail_stack_type fail_stack
;
3902 static unsigned failure_id
;
3903 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
3907 /* This holds the pointer to the failure stack, when
3908 it is allocated relocatably. */
3909 fail_stack_elt_t
*failure_stack_ptr
;
3912 /* We fill all the registers internally, independent of what we
3913 return, for use in backreferences. The number here includes
3914 an element for register zero. */
3915 size_t num_regs
= bufp
->re_nsub
+ 1;
3917 /* The currently active registers. */
3918 active_reg_t lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
3919 active_reg_t highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
3921 /* Information on the contents of registers. These are pointers into
3922 the input strings; they record just what was matched (on this
3923 attempt) by a subexpression part of the pattern, that is, the
3924 regnum-th regstart pointer points to where in the pattern we began
3925 matching and the regnum-th regend points to right after where we
3926 stopped matching the regnum-th subexpression. (The zeroth register
3927 keeps track of what the whole pattern matches.) */
3928 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3929 const char **regstart
, **regend
;
3932 /* If a group that's operated upon by a repetition operator fails to
3933 match anything, then the register for its start will need to be
3934 restored because it will have been set to wherever in the string we
3935 are when we last see its open-group operator. Similarly for a
3937 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3938 const char **old_regstart
, **old_regend
;
3941 /* The is_active field of reg_info helps us keep track of which (possibly
3942 nested) subexpressions we are currently in. The matched_something
3943 field of reg_info[reg_num] helps us tell whether or not we have
3944 matched any of the pattern so far this time through the reg_num-th
3945 subexpression. These two fields get reset each time through any
3946 loop their register is in. */
3947 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
3948 register_info_type
*reg_info
;
3951 /* The following record the register info as found in the above
3952 variables when we find a match better than any we've seen before.
3953 This happens as we backtrack through the failure points, which in
3954 turn happens only if we have not yet matched the entire string. */
3955 unsigned best_regs_set
= false;
3956 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3957 const char **best_regstart
, **best_regend
;
3960 /* Logically, this is `best_regend[0]'. But we don't want to have to
3961 allocate space for that if we're not allocating space for anything
3962 else (see below). Also, we never need info about register 0 for
3963 any of the other register vectors, and it seems rather a kludge to
3964 treat `best_regend' differently than the rest. So we keep track of
3965 the end of the best match so far in a separate variable. We
3966 initialize this to NULL so that when we backtrack the first time
3967 and need to test it, it's not garbage. */
3968 const char *match_end
= NULL
;
3970 /* This helps SET_REGS_MATCHED avoid doing redundant work. */
3971 int set_regs_matched_done
= 0;
3973 /* Used when we pop values we don't care about. */
3974 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
3975 const char **reg_dummy
;
3976 register_info_type
*reg_info_dummy
;
3980 /* Counts the total number of registers pushed. */
3981 unsigned num_regs_pushed
= 0;
3984 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3988 #ifdef MATCH_MAY_ALLOCATE
3989 /* Do not bother to initialize all the register variables if there are
3990 no groups in the pattern, as it takes a fair amount of time. If
3991 there are groups, we include space for register 0 (the whole
3992 pattern), even though we never use it, since it simplifies the
3993 array indexing. We should fix this. */
3996 regstart
= REGEX_TALLOC (num_regs
, const char *);
3997 regend
= REGEX_TALLOC (num_regs
, const char *);
3998 old_regstart
= REGEX_TALLOC (num_regs
, const char *);
3999 old_regend
= REGEX_TALLOC (num_regs
, const char *);
4000 best_regstart
= REGEX_TALLOC (num_regs
, const char *);
4001 best_regend
= REGEX_TALLOC (num_regs
, const char *);
4002 reg_info
= REGEX_TALLOC (num_regs
, register_info_type
);
4003 reg_dummy
= REGEX_TALLOC (num_regs
, const char *);
4004 reg_info_dummy
= REGEX_TALLOC (num_regs
, register_info_type
);
4006 if (!(regstart
&& regend
&& old_regstart
&& old_regend
&& reg_info
4007 && best_regstart
&& best_regend
&& reg_dummy
&& reg_info_dummy
))
4015 /* We must initialize all our variables to NULL, so that
4016 `FREE_VARIABLES' doesn't try to free them. */
4017 regstart
= regend
= old_regstart
= old_regend
= best_regstart
4018 = best_regend
= reg_dummy
= NULL
;
4019 reg_info
= reg_info_dummy
= (register_info_type
*) NULL
;
4021 #endif /* MATCH_MAY_ALLOCATE */
4023 /* The starting position is bogus. */
4024 if (pos
< 0 || pos
> size1
+ size2
)
4030 /* Initialize subexpression text positions to -1 to mark ones that no
4031 start_memory/stop_memory has been seen for. Also initialize the
4032 register information struct. */
4033 for (mcnt
= 1; (unsigned) mcnt
< num_regs
; mcnt
++)
4035 regstart
[mcnt
] = regend
[mcnt
]
4036 = old_regstart
[mcnt
] = old_regend
[mcnt
] = REG_UNSET_VALUE
;
4038 REG_MATCH_NULL_STRING_P (reg_info
[mcnt
]) = MATCH_NULL_UNSET_VALUE
;
4039 IS_ACTIVE (reg_info
[mcnt
]) = 0;
4040 MATCHED_SOMETHING (reg_info
[mcnt
]) = 0;
4041 EVER_MATCHED_SOMETHING (reg_info
[mcnt
]) = 0;
4044 /* We move `string1' into `string2' if the latter's empty -- but not if
4045 `string1' is null. */
4046 if (size2
== 0 && string1
!= NULL
)
4053 end1
= string1
+ size1
;
4054 end2
= string2
+ size2
;
4056 /* Compute where to stop matching, within the two strings. */
4059 end_match_1
= string1
+ stop
;
4060 end_match_2
= string2
;
4065 end_match_2
= string2
+ stop
- size1
;
4068 /* `p' scans through the pattern as `d' scans through the data.
4069 `dend' is the end of the input string that `d' points within. `d'
4070 is advanced into the following input string whenever necessary, but
4071 this happens before fetching; therefore, at the beginning of the
4072 loop, `d' can be pointing at the end of a string, but it cannot
4074 if (size1
> 0 && pos
<= size1
)
4081 d
= string2
+ pos
- size1
;
4085 DEBUG_PRINT1 ("The compiled pattern is:\n");
4086 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4087 DEBUG_PRINT1 ("The string to match is: `");
4088 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4089 DEBUG_PRINT1 ("'\n");
4091 /* This loops over pattern commands. It exits by returning from the
4092 function if the match is complete, or it drops through if the match
4093 fails at this starting point in the input data. */
4097 DEBUG_PRINT2 ("\n%p: ", p
);
4099 DEBUG_PRINT2 ("\n0x%x: ", p
);
4103 { /* End of pattern means we might have succeeded. */
4104 DEBUG_PRINT1 ("end of pattern ... ");
4106 /* If we haven't matched the entire string, and we want the
4107 longest match, try backtracking. */
4108 if (d
!= end_match_2
)
4110 /* 1 if this match ends in the same string (string1 or string2)
4111 as the best previous match. */
4112 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4113 == MATCHING_IN_FIRST_STRING
);
4114 /* 1 if this match is the best seen so far. */
4115 boolean best_match_p
;
4117 /* AIX compiler got confused when this was combined
4118 with the previous declaration. */
4120 best_match_p
= d
> match_end
;
4122 best_match_p
= !MATCHING_IN_FIRST_STRING
;
4124 DEBUG_PRINT1 ("backtracking.\n");
4126 if (!FAIL_STACK_EMPTY ())
4127 { /* More failure points to try. */
4129 /* If exceeds best match so far, save it. */
4130 if (!best_regs_set
|| best_match_p
)
4132 best_regs_set
= true;
4135 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4137 for (mcnt
= 1; (unsigned) mcnt
< num_regs
; mcnt
++)
4139 best_regstart
[mcnt
] = regstart
[mcnt
];
4140 best_regend
[mcnt
] = regend
[mcnt
];
4146 /* If no failure points, don't restore garbage. And if
4147 last match is real best match, don't restore second
4149 else if (best_regs_set
&& !best_match_p
)
4152 /* Restore best match. It may happen that `dend ==
4153 end_match_1' while the restored d is in string2.
4154 For example, the pattern `x.*y.*z' against the
4155 strings `x-' and `y-z-', if the two strings are
4156 not consecutive in memory. */
4157 DEBUG_PRINT1 ("Restoring best registers.\n");
4160 dend
= ((d
>= string1
&& d
<= end1
)
4161 ? end_match_1
: end_match_2
);
4163 for (mcnt
= 1; (unsigned) mcnt
< num_regs
; mcnt
++)
4165 regstart
[mcnt
] = best_regstart
[mcnt
];
4166 regend
[mcnt
] = best_regend
[mcnt
];
4169 } /* d != end_match_2 */
4172 DEBUG_PRINT1 ("Accepting match.\n");
4174 /* If caller wants register contents data back, do it. */
4175 if (regs
&& !bufp
->no_sub
)
4177 /* Have the register data arrays been allocated? */
4178 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4179 { /* No. So allocate them with malloc. We need one
4180 extra element beyond `num_regs' for the `-1' marker
4182 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4183 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4184 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4185 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4190 bufp
->regs_allocated
= REGS_REALLOCATE
;
4192 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4193 { /* Yes. If we need more elements than were already
4194 allocated, reallocate them. If we need fewer, just
4196 if (regs
->num_regs
< num_regs
+ 1)
4198 regs
->num_regs
= num_regs
+ 1;
4199 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4200 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4201 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4210 /* These braces fend off a "empty body in an else-statement"
4211 warning under GCC when assert expands to nothing. */
4212 assert (bufp
->regs_allocated
== REGS_FIXED
);
4215 /* Convert the pointer data in `regstart' and `regend' to
4216 indices. Register zero has to be set differently,
4217 since we haven't kept track of any info for it. */
4218 if (regs
->num_regs
> 0)
4220 regs
->start
[0] = pos
;
4221 regs
->end
[0] = (MATCHING_IN_FIRST_STRING
4222 ? ((regoff_t
) (d
- string1
))
4223 : ((regoff_t
) (d
- string2
+ size1
)));
4226 /* Go through the first `min (num_regs, regs->num_regs)'
4227 registers, since that is all we initialized. */
4228 for (mcnt
= 1; (unsigned) mcnt
< MIN (num_regs
, regs
->num_regs
);
4231 if (REG_UNSET (regstart
[mcnt
]) || REG_UNSET (regend
[mcnt
]))
4232 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4236 = (regoff_t
) POINTER_TO_OFFSET (regstart
[mcnt
]);
4238 = (regoff_t
) POINTER_TO_OFFSET (regend
[mcnt
]);
4242 /* If the regs structure we return has more elements than
4243 were in the pattern, set the extra elements to -1. If
4244 we (re)allocated the registers, this is the case,
4245 because we always allocate enough to have at least one
4247 for (mcnt
= num_regs
; (unsigned) mcnt
< regs
->num_regs
; mcnt
++)
4248 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4249 } /* regs && !bufp->no_sub */
4251 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4252 nfailure_points_pushed
, nfailure_points_popped
,
4253 nfailure_points_pushed
- nfailure_points_popped
);
4254 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4256 mcnt
= d
- pos
- (MATCHING_IN_FIRST_STRING
4260 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4266 /* Otherwise match next pattern command. */
4267 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4269 /* Ignore these. Used to ignore the n of succeed_n's which
4270 currently have n == 0. */
4272 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4276 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4279 /* Match the next n pattern characters exactly. The following
4280 byte in the pattern defines n, and the n bytes after that
4281 are the characters to match. */
4284 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4286 /* This is written out as an if-else so we don't waste time
4287 testing `translate' inside the loop. */
4293 if ((unsigned char) translate
[(unsigned char) *d
++]
4294 != (unsigned char) *p
++)
4304 if (*d
++ != (char) *p
++) goto fail
;
4308 SET_REGS_MATCHED ();
4312 /* Match any character except possibly a newline or a null. */
4314 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4318 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
) && TRANSLATE (*d
) == '\n')
4319 || (bufp
->syntax
& RE_DOT_NOT_NULL
&& TRANSLATE (*d
) == '\000'))
4322 SET_REGS_MATCHED ();
4323 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4331 register unsigned char c
;
4332 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4334 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4337 c
= TRANSLATE (*d
); /* The character to match. */
4339 /* Cast to `unsigned' instead of `unsigned char' in case the
4340 bit list is a full 32 bytes long. */
4341 if (c
< (unsigned) (*p
* BYTEWIDTH
)
4342 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4347 if (!not) goto fail
;
4349 SET_REGS_MATCHED ();
4355 /* The beginning of a group is represented by start_memory.
4356 The arguments are the register number in the next byte, and the
4357 number of groups inner to this one in the next. The text
4358 matched within the group is recorded (in the internal
4359 registers data structure) under the register number. */
4361 DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p
, p
[1]);
4363 /* Find out if this group can match the empty string. */
4364 p1
= p
; /* To send to group_match_null_string_p. */
4366 if (REG_MATCH_NULL_STRING_P (reg_info
[*p
]) == MATCH_NULL_UNSET_VALUE
)
4367 REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4368 = group_match_null_string_p (&p1
, pend
, reg_info
);
4370 /* Save the position in the string where we were the last time
4371 we were at this open-group operator in case the group is
4372 operated upon by a repetition operator, e.g., with `(a*)*b'
4373 against `ab'; then we want to ignore where we are now in
4374 the string in case this attempt to match fails. */
4375 old_regstart
[*p
] = REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4376 ? REG_UNSET (regstart
[*p
]) ? d
: regstart
[*p
]
4378 DEBUG_PRINT2 (" old_regstart: %d\n",
4379 POINTER_TO_OFFSET (old_regstart
[*p
]));
4382 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
4384 IS_ACTIVE (reg_info
[*p
]) = 1;
4385 MATCHED_SOMETHING (reg_info
[*p
]) = 0;
4387 /* Clear this whenever we change the register activity status. */
4388 set_regs_matched_done
= 0;
4390 /* This is the new highest active register. */
4391 highest_active_reg
= *p
;
4393 /* If nothing was active before, this is the new lowest active
4395 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
4396 lowest_active_reg
= *p
;
4398 /* Move past the register number and inner group count. */
4400 just_past_start_mem
= p
;
4405 /* The stop_memory opcode represents the end of a group. Its
4406 arguments are the same as start_memory's: the register
4407 number, and the number of inner groups. */
4409 DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p
, p
[1]);
4411 /* We need to save the string position the last time we were at
4412 this close-group operator in case the group is operated
4413 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4414 against `aba'; then we want to ignore where we are now in
4415 the string in case this attempt to match fails. */
4416 old_regend
[*p
] = REG_MATCH_NULL_STRING_P (reg_info
[*p
])
4417 ? REG_UNSET (regend
[*p
]) ? d
: regend
[*p
]
4419 DEBUG_PRINT2 (" old_regend: %d\n",
4420 POINTER_TO_OFFSET (old_regend
[*p
]));
4423 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
4425 /* This register isn't active anymore. */
4426 IS_ACTIVE (reg_info
[*p
]) = 0;
4428 /* Clear this whenever we change the register activity status. */
4429 set_regs_matched_done
= 0;
4431 /* If this was the only register active, nothing is active
4433 if (lowest_active_reg
== highest_active_reg
)
4435 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
4436 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
4439 { /* We must scan for the new highest active register, since
4440 it isn't necessarily one less than now: consider
4441 (a(b)c(d(e)f)g). When group 3 ends, after the f), the
4442 new highest active register is 1. */
4443 unsigned char r
= *p
- 1;
4444 while (r
> 0 && !IS_ACTIVE (reg_info
[r
]))
4447 /* If we end up at register zero, that means that we saved
4448 the registers as the result of an `on_failure_jump', not
4449 a `start_memory', and we jumped to past the innermost
4450 `stop_memory'. For example, in ((.)*) we save
4451 registers 1 and 2 as a result of the *, but when we pop
4452 back to the second ), we are at the stop_memory 1.
4453 Thus, nothing is active. */
4456 lowest_active_reg
= NO_LOWEST_ACTIVE_REG
;
4457 highest_active_reg
= NO_HIGHEST_ACTIVE_REG
;
4460 highest_active_reg
= r
;
4463 /* If just failed to match something this time around with a
4464 group that's operated on by a repetition operator, try to
4465 force exit from the ``loop'', and restore the register
4466 information for this group that we had before trying this
4468 if ((!MATCHED_SOMETHING (reg_info
[*p
])
4469 || just_past_start_mem
== p
- 1)
4472 boolean is_a_jump_n
= false;
4476 switch ((re_opcode_t
) *p1
++)
4480 case pop_failure_jump
:
4481 case maybe_pop_jump
:
4483 case dummy_failure_jump
:
4484 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4494 /* If the next operation is a jump backwards in the pattern
4495 to an on_failure_jump right before the start_memory
4496 corresponding to this stop_memory, exit from the loop
4497 by forcing a failure after pushing on the stack the
4498 on_failure_jump's jump in the pattern, and d. */
4499 if (mcnt
< 0 && (re_opcode_t
) *p1
== on_failure_jump
4500 && (re_opcode_t
) p1
[3] == start_memory
&& p1
[4] == *p
)
4502 /* If this group ever matched anything, then restore
4503 what its registers were before trying this last
4504 failed match, e.g., with `(a*)*b' against `ab' for
4505 regstart[1], and, e.g., with `((a*)*(b*)*)*'
4506 against `aba' for regend[3].
4508 Also restore the registers for inner groups for,
4509 e.g., `((a*)(b*))*' against `aba' (register 3 would
4510 otherwise get trashed). */
4512 if (EVER_MATCHED_SOMETHING (reg_info
[*p
]))
4516 EVER_MATCHED_SOMETHING (reg_info
[*p
]) = 0;
4518 /* Restore this and inner groups' (if any) registers. */
4519 for (r
= *p
; r
< (unsigned) *p
+ (unsigned) *(p
+ 1);
4522 regstart
[r
] = old_regstart
[r
];
4524 /* xx why this test? */
4525 if (old_regend
[r
] >= regstart
[r
])
4526 regend
[r
] = old_regend
[r
];
4530 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
4531 PUSH_FAILURE_POINT (p1
+ mcnt
, d
, -2);
4537 /* Move past the register number and the inner group count. */
4542 /* \<digit> has been turned into a `duplicate' command which is
4543 followed by the numeric value of <digit> as the register number. */
4546 register const char *d2
, *dend2
;
4547 int regno
= *p
++; /* Get which register to match against. */
4548 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
4550 /* Can't back reference a group which we've never matched. */
4551 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
4554 /* Where in input to try to start matching. */
4555 d2
= regstart
[regno
];
4557 /* Where to stop matching; if both the place to start and
4558 the place to stop matching are in the same string, then
4559 set to the place to stop, otherwise, for now have to use
4560 the end of the first string. */
4562 dend2
= ((FIRST_STRING_P (regstart
[regno
])
4563 == FIRST_STRING_P (regend
[regno
]))
4564 ? regend
[regno
] : end_match_1
);
4567 /* If necessary, advance to next segment in register
4571 if (dend2
== end_match_2
) break;
4572 if (dend2
== regend
[regno
]) break;
4574 /* End of string1 => advance to string2. */
4576 dend2
= regend
[regno
];
4578 /* At end of register contents => success */
4579 if (d2
== dend2
) break;
4581 /* If necessary, advance to next segment in data. */
4584 /* How many characters left in this segment to match. */
4587 /* Want how many consecutive characters we can match in
4588 one shot, so, if necessary, adjust the count. */
4589 if (mcnt
> dend2
- d2
)
4592 /* Compare that many; failure if mismatch, else move
4595 ? bcmp_translate (d
, d2
, mcnt
, translate
)
4596 : memcmp (d
, d2
, mcnt
))
4598 d
+= mcnt
, d2
+= mcnt
;
4600 /* Do this because we've match some characters. */
4601 SET_REGS_MATCHED ();
4607 /* begline matches the empty string at the beginning of the string
4608 (unless `not_bol' is set in `bufp'), and, if
4609 `newline_anchor' is set, after newlines. */
4611 DEBUG_PRINT1 ("EXECUTING begline.\n");
4613 if (AT_STRINGS_BEG (d
))
4615 if (!bufp
->not_bol
) break;
4617 else if (d
[-1] == '\n' && bufp
->newline_anchor
)
4621 /* In all other cases, we fail. */
4625 /* endline is the dual of begline. */
4627 DEBUG_PRINT1 ("EXECUTING endline.\n");
4629 if (AT_STRINGS_END (d
))
4631 if (!bufp
->not_eol
) break;
4634 /* We have to ``prefetch'' the next character. */
4635 else if ((d
== end1
? *string2
: *d
) == '\n'
4636 && bufp
->newline_anchor
)
4643 /* Match at the very beginning of the data. */
4645 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4646 if (AT_STRINGS_BEG (d
))
4651 /* Match at the very end of the data. */
4653 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4654 if (AT_STRINGS_END (d
))
4659 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
4660 pushes NULL as the value for the string on the stack. Then
4661 `pop_failure_point' will keep the current value for the
4662 string, instead of restoring it. To see why, consider
4663 matching `foo\nbar' against `.*\n'. The .* matches the foo;
4664 then the . fails against the \n. But the next thing we want
4665 to do is match the \n against the \n; if we restored the
4666 string value, we would be back at the foo.
4668 Because this is used only in specific cases, we don't need to
4669 check all the things that `on_failure_jump' does, to make
4670 sure the right things get saved on the stack. Hence we don't
4671 share its code. The only reason to push anything on the
4672 stack at all is that otherwise we would have to change
4673 `anychar's code to do something besides goto fail in this
4674 case; that seems worse than this. */
4675 case on_failure_keep_string_jump
:
4676 DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4678 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4680 DEBUG_PRINT3 (" %d (to %p):\n", mcnt
, p
+ mcnt
);
4682 DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt
, p
+ mcnt
);
4685 PUSH_FAILURE_POINT (p
+ mcnt
, NULL
, -2);
4689 /* Uses of on_failure_jump:
4691 Each alternative starts with an on_failure_jump that points
4692 to the beginning of the next alternative. Each alternative
4693 except the last ends with a jump that in effect jumps past
4694 the rest of the alternatives. (They really jump to the
4695 ending jump of the following alternative, because tensioning
4696 these jumps is a hassle.)
4698 Repeats start with an on_failure_jump that points past both
4699 the repetition text and either the following jump or
4700 pop_failure_jump back to this on_failure_jump. */
4701 case on_failure_jump
:
4703 DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4705 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4707 DEBUG_PRINT3 (" %d (to %p)", mcnt
, p
+ mcnt
);
4709 DEBUG_PRINT3 (" %d (to 0x%x)", mcnt
, p
+ mcnt
);
4712 /* If this on_failure_jump comes right before a group (i.e.,
4713 the original * applied to a group), save the information
4714 for that group and all inner ones, so that if we fail back
4715 to this point, the group's information will be correct.
4716 For example, in \(a*\)*\1, we need the preceding group,
4717 and in \(zz\(a*\)b*\)\2, we need the inner group. */
4719 /* We can't use `p' to check ahead because we push
4720 a failure point to `p + mcnt' after we do this. */
4723 /* We need to skip no_op's before we look for the
4724 start_memory in case this on_failure_jump is happening as
4725 the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4727 while (p1
< pend
&& (re_opcode_t
) *p1
== no_op
)
4730 if (p1
< pend
&& (re_opcode_t
) *p1
== start_memory
)
4732 /* We have a new highest active register now. This will
4733 get reset at the start_memory we are about to get to,
4734 but we will have saved all the registers relevant to
4735 this repetition op, as described above. */
4736 highest_active_reg
= *(p1
+ 1) + *(p1
+ 2);
4737 if (lowest_active_reg
== NO_LOWEST_ACTIVE_REG
)
4738 lowest_active_reg
= *(p1
+ 1);
4741 DEBUG_PRINT1 (":\n");
4742 PUSH_FAILURE_POINT (p
+ mcnt
, d
, -2);
4746 /* A smart repeat ends with `maybe_pop_jump'.
4747 We change it to either `pop_failure_jump' or `jump'. */
4748 case maybe_pop_jump
:
4749 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4750 DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt
);
4752 register unsigned char *p2
= p
;
4754 /* Compare the beginning of the repeat with what in the
4755 pattern follows its end. If we can establish that there
4756 is nothing that they would both match, i.e., that we
4757 would have to backtrack because of (as in, e.g., `a*a')
4758 then we can change to pop_failure_jump, because we'll
4759 never have to backtrack.
4761 This is not true in the case of alternatives: in
4762 `(a|ab)*' we do need to backtrack to the `ab' alternative
4763 (e.g., if the string was `ab'). But instead of trying to
4764 detect that here, the alternative has put on a dummy
4765 failure point which is what we will end up popping. */
4767 /* Skip over open/close-group commands.
4768 If what follows this loop is a ...+ construct,
4769 look at what begins its body, since we will have to
4770 match at least one of that. */
4774 && ((re_opcode_t
) *p2
== stop_memory
4775 || (re_opcode_t
) *p2
== start_memory
))
4777 else if (p2
+ 6 < pend
4778 && (re_opcode_t
) *p2
== dummy_failure_jump
)
4785 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4786 to the `maybe_finalize_jump' of this case. Examine what
4789 /* If we're at the end of the pattern, we can change. */
4792 /* Consider what happens when matching ":\(.*\)"
4793 against ":/". I don't really understand this code
4795 p
[-3] = (unsigned char) pop_failure_jump
;
4797 (" End of pattern: change to `pop_failure_jump'.\n");
4800 else if ((re_opcode_t
) *p2
== exactn
4801 || (bufp
->newline_anchor
&& (re_opcode_t
) *p2
== endline
))
4803 register unsigned char c
4804 = *p2
== (unsigned char) endline
? '\n' : p2
[2];
4806 if ((re_opcode_t
) p1
[3] == exactn
&& p1
[5] != c
)
4808 p
[-3] = (unsigned char) pop_failure_jump
;
4809 DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n",
4813 else if ((re_opcode_t
) p1
[3] == charset
4814 || (re_opcode_t
) p1
[3] == charset_not
)
4816 int not = (re_opcode_t
) p1
[3] == charset_not
;
4818 if (c
< (unsigned char) (p1
[4] * BYTEWIDTH
)
4819 && p1
[5 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4822 /* `not' is equal to 1 if c would match, which means
4823 that we can't change to pop_failure_jump. */
4826 p
[-3] = (unsigned char) pop_failure_jump
;
4827 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4831 else if ((re_opcode_t
) *p2
== charset
)
4833 /* We win if the first character of the loop is not part
4835 if ((re_opcode_t
) p1
[3] == exactn
4836 && ! ((int) p2
[1] * BYTEWIDTH
> (int) p1
[5]
4837 && (p2
[2 + p1
[5] / BYTEWIDTH
]
4838 & (1 << (p1
[5] % BYTEWIDTH
)))))
4840 p
[-3] = (unsigned char) pop_failure_jump
;
4841 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4844 else if ((re_opcode_t
) p1
[3] == charset_not
)
4847 /* We win if the charset_not inside the loop
4848 lists every character listed in the charset after. */
4849 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4850 if (! (p2
[2 + idx
] == 0
4851 || (idx
< (int) p1
[4]
4852 && ((p2
[2 + idx
] & ~ p1
[5 + idx
]) == 0))))
4857 p
[-3] = (unsigned char) pop_failure_jump
;
4858 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4861 else if ((re_opcode_t
) p1
[3] == charset
)
4864 /* We win if the charset inside the loop
4865 has no overlap with the one after the loop. */
4867 idx
< (int) p2
[1] && idx
< (int) p1
[4];
4869 if ((p2
[2 + idx
] & p1
[5 + idx
]) != 0)
4872 if (idx
== p2
[1] || idx
== p1
[4])
4874 p
[-3] = (unsigned char) pop_failure_jump
;
4875 DEBUG_PRINT1 (" No match => pop_failure_jump.\n");
4880 p
-= 2; /* Point at relative address again. */
4881 if ((re_opcode_t
) p
[-1] != pop_failure_jump
)
4883 p
[-1] = (unsigned char) jump
;
4884 DEBUG_PRINT1 (" Match => jump.\n");
4885 goto unconditional_jump
;
4887 /* Note fall through. */
4890 /* The end of a simple repeat has a pop_failure_jump back to
4891 its matching on_failure_jump, where the latter will push a
4892 failure point. The pop_failure_jump takes off failure
4893 points put on by this pop_failure_jump's matching
4894 on_failure_jump; we got through the pattern to here from the
4895 matching on_failure_jump, so didn't fail. */
4896 case pop_failure_jump
:
4898 /* We need to pass separate storage for the lowest and
4899 highest registers, even though we don't care about the
4900 actual values. Otherwise, we will restore only one
4901 register from the stack, since lowest will == highest in
4902 `pop_failure_point'. */
4903 active_reg_t dummy_low_reg
, dummy_high_reg
;
4904 unsigned char *pdummy
;
4907 DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4908 POP_FAILURE_POINT (sdummy
, pdummy
,
4909 dummy_low_reg
, dummy_high_reg
,
4910 reg_dummy
, reg_dummy
, reg_info_dummy
);
4912 /* Note fall through. */
4916 DEBUG_PRINT2 ("\n%p: ", p
);
4918 DEBUG_PRINT2 ("\n0x%x: ", p
);
4920 /* Note fall through. */
4922 /* Unconditionally jump (without popping any failure points). */
4924 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
4925 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
4926 p
+= mcnt
; /* Do the jump. */
4928 DEBUG_PRINT2 ("(to %p).\n", p
);
4930 DEBUG_PRINT2 ("(to 0x%x).\n", p
);
4935 /* We need this opcode so we can detect where alternatives end
4936 in `group_match_null_string_p' et al. */
4938 DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4939 goto unconditional_jump
;
4942 /* Normally, the on_failure_jump pushes a failure point, which
4943 then gets popped at pop_failure_jump. We will end up at
4944 pop_failure_jump, also, and with a pattern of, say, `a+', we
4945 are skipping over the on_failure_jump, so we have to push
4946 something meaningless for pop_failure_jump to pop. */
4947 case dummy_failure_jump
:
4948 DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4949 /* It doesn't matter what we push for the string here. What
4950 the code at `fail' tests is the value for the pattern. */
4951 PUSH_FAILURE_POINT (NULL
, NULL
, -2);
4952 goto unconditional_jump
;
4955 /* At the end of an alternative, we need to push a dummy failure
4956 point in case we are followed by a `pop_failure_jump', because
4957 we don't want the failure point for the alternative to be
4958 popped. For example, matching `(a|ab)*' against `aab'
4959 requires that we match the `ab' alternative. */
4960 case push_dummy_failure
:
4961 DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4962 /* See comments just above at `dummy_failure_jump' about the
4964 PUSH_FAILURE_POINT (NULL
, NULL
, -2);
4967 /* Have to succeed matching what follows at least n times.
4968 After that, handle like `on_failure_jump'. */
4970 EXTRACT_NUMBER (mcnt
, p
+ 2);
4971 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
4974 /* Originally, this is how many times we HAVE to succeed. */
4979 STORE_NUMBER_AND_INCR (p
, mcnt
);
4981 DEBUG_PRINT3 (" Setting %p to %d.\n", p
- 2, mcnt
);
4983 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p
- 2, mcnt
);
4989 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p
+2);
4991 DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p
+2);
4993 p
[2] = (unsigned char) no_op
;
4994 p
[3] = (unsigned char) no_op
;
5000 EXTRACT_NUMBER (mcnt
, p
+ 2);
5001 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5003 /* Originally, this is how many times we CAN jump. */
5007 STORE_NUMBER (p
+ 2, mcnt
);
5009 DEBUG_PRINT3 (" Setting %p to %d.\n", p
+ 2, mcnt
);
5011 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p
+ 2, mcnt
);
5013 goto unconditional_jump
;
5015 /* If don't have to jump any more, skip over the rest of command. */
5022 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5024 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5026 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5028 DEBUG_PRINT3 (" Setting %p to %d.\n", p1
, mcnt
);
5030 DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1
, mcnt
);
5032 STORE_NUMBER (p1
, mcnt
);
5037 /* The DEC Alpha C compiler 3.x generates incorrect code for the
5038 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
5039 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
5040 macro and introducing temporary variables works around the bug. */
5043 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5044 if (AT_WORD_BOUNDARY (d
))
5049 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5050 if (AT_WORD_BOUNDARY (d
))
5056 boolean prevchar
, thischar
;
5058 DEBUG_PRINT1 ("EXECUTING wordbound.\n");
5059 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5062 prevchar
= WORDCHAR_P (d
- 1);
5063 thischar
= WORDCHAR_P (d
);
5064 if (prevchar
!= thischar
)
5071 boolean prevchar
, thischar
;
5073 DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
5074 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5077 prevchar
= WORDCHAR_P (d
- 1);
5078 thischar
= WORDCHAR_P (d
);
5079 if (prevchar
!= thischar
)
5086 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5087 if (WORDCHAR_P (d
) && (AT_STRINGS_BEG (d
) || !WORDCHAR_P (d
- 1)))
5092 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5093 if (!AT_STRINGS_BEG (d
) && WORDCHAR_P (d
- 1)
5094 && (!WORDCHAR_P (d
) || AT_STRINGS_END (d
)))
5100 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5101 if (PTR_CHAR_POS ((unsigned char *) d
) >= point
)
5106 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5107 if (PTR_CHAR_POS ((unsigned char *) d
) != point
)
5112 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5113 if (PTR_CHAR_POS ((unsigned char *) d
) <= point
)
5118 DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt
);
5123 DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
5127 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5129 if (SYNTAX (d
[-1]) != (enum syntaxcode
) mcnt
)
5131 SET_REGS_MATCHED ();
5135 DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt
);
5137 goto matchnotsyntax
;
5140 DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
5144 /* Can't use *d++ here; SYNTAX may be an unsafe macro. */
5146 if (SYNTAX (d
[-1]) == (enum syntaxcode
) mcnt
)
5148 SET_REGS_MATCHED ();
5151 #else /* not emacs */
5153 DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
5155 if (!WORDCHAR_P (d
))
5157 SET_REGS_MATCHED ();
5162 DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
5166 SET_REGS_MATCHED ();
5169 #endif /* not emacs */
5174 continue; /* Successfully executed one pattern command; keep going. */
5177 /* We goto here if a matching operation fails. */
5179 if (!FAIL_STACK_EMPTY ())
5180 { /* A restart point is known. Restore to that state. */
5181 DEBUG_PRINT1 ("\nFAIL:\n");
5182 POP_FAILURE_POINT (d
, p
,
5183 lowest_active_reg
, highest_active_reg
,
5184 regstart
, regend
, reg_info
);
5186 /* If this failure point is a dummy, try the next one. */
5190 /* If we failed to the end of the pattern, don't examine *p. */
5194 boolean is_a_jump_n
= false;
5196 /* If failed to a backwards jump that's part of a repetition
5197 loop, need to pop this failure point and use the next one. */
5198 switch ((re_opcode_t
) *p
)
5202 case maybe_pop_jump
:
5203 case pop_failure_jump
:
5206 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5209 if ((is_a_jump_n
&& (re_opcode_t
) *p1
== succeed_n
)
5211 && (re_opcode_t
) *p1
== on_failure_jump
))
5219 if (d
>= string1
&& d
<= end1
)
5223 break; /* Matching at this starting point really fails. */
5227 goto restore_best_regs
;
5231 return -1; /* Failure to match. */
5234 /* Subroutine definitions for re_match_2. */
5237 /* We are passed P pointing to a register number after a start_memory.
5239 Return true if the pattern up to the corresponding stop_memory can
5240 match the empty string, and false otherwise.
5242 If we find the matching stop_memory, sets P to point to one past its number.
5243 Otherwise, sets P to an undefined byte less than or equal to END.
5245 We don't handle duplicates properly (yet). */
5248 group_match_null_string_p (p
, end
, reg_info
)
5249 unsigned char **p
, *end
;
5250 register_info_type
*reg_info
;
5253 /* Point to after the args to the start_memory. */
5254 unsigned char *p1
= *p
+ 2;
5258 /* Skip over opcodes that can match nothing, and return true or
5259 false, as appropriate, when we get to one that can't, or to the
5260 matching stop_memory. */
5262 switch ((re_opcode_t
) *p1
)
5264 /* Could be either a loop or a series of alternatives. */
5265 case on_failure_jump
:
5267 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5269 /* If the next operation is not a jump backwards in the
5274 /* Go through the on_failure_jumps of the alternatives,
5275 seeing if any of the alternatives cannot match nothing.
5276 The last alternative starts with only a jump,
5277 whereas the rest start with on_failure_jump and end
5278 with a jump, e.g., here is the pattern for `a|b|c':
5280 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
5281 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
5284 So, we have to first go through the first (n-1)
5285 alternatives and then deal with the last one separately. */
5288 /* Deal with the first (n-1) alternatives, which start
5289 with an on_failure_jump (see above) that jumps to right
5290 past a jump_past_alt. */
5292 while ((re_opcode_t
) p1
[mcnt
-3] == jump_past_alt
)
5294 /* `mcnt' holds how many bytes long the alternative
5295 is, including the ending `jump_past_alt' and
5298 if (!alt_match_null_string_p (p1
, p1
+ mcnt
- 3,
5302 /* Move to right after this alternative, including the
5306 /* Break if it's the beginning of an n-th alternative
5307 that doesn't begin with an on_failure_jump. */
5308 if ((re_opcode_t
) *p1
!= on_failure_jump
)
5311 /* Still have to check that it's not an n-th
5312 alternative that starts with an on_failure_jump. */
5314 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5315 if ((re_opcode_t
) p1
[mcnt
-3] != jump_past_alt
)
5317 /* Get to the beginning of the n-th alternative. */
5323 /* Deal with the last alternative: go back and get number
5324 of the `jump_past_alt' just before it. `mcnt' contains
5325 the length of the alternative. */
5326 EXTRACT_NUMBER (mcnt
, p1
- 2);
5328 if (!alt_match_null_string_p (p1
, p1
+ mcnt
, reg_info
))
5331 p1
+= mcnt
; /* Get past the n-th alternative. */
5337 assert (p1
[1] == **p
);
5343 if (!common_op_match_null_string_p (&p1
, end
, reg_info
))
5346 } /* while p1 < end */
5349 } /* group_match_null_string_p */
5352 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
5353 It expects P to be the first byte of a single alternative and END one
5354 byte past the last. The alternative can contain groups. */
5357 alt_match_null_string_p (p
, end
, reg_info
)
5358 unsigned char *p
, *end
;
5359 register_info_type
*reg_info
;
5362 unsigned char *p1
= p
;
5366 /* Skip over opcodes that can match nothing, and break when we get
5367 to one that can't. */
5369 switch ((re_opcode_t
) *p1
)
5372 case on_failure_jump
:
5374 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5379 if (!common_op_match_null_string_p (&p1
, end
, reg_info
))
5382 } /* while p1 < end */
5385 } /* alt_match_null_string_p */
5388 /* Deals with the ops common to group_match_null_string_p and
5389 alt_match_null_string_p.
5391 Sets P to one after the op and its arguments, if any. */
5394 common_op_match_null_string_p (p
, end
, reg_info
)
5395 unsigned char **p
, *end
;
5396 register_info_type
*reg_info
;
5401 unsigned char *p1
= *p
;
5403 switch ((re_opcode_t
) *p1
++)
5423 assert (reg_no
> 0 && reg_no
<= MAX_REGNUM
);
5424 ret
= group_match_null_string_p (&p1
, end
, reg_info
);
5426 /* Have to set this here in case we're checking a group which
5427 contains a group and a back reference to it. */
5429 if (REG_MATCH_NULL_STRING_P (reg_info
[reg_no
]) == MATCH_NULL_UNSET_VALUE
)
5430 REG_MATCH_NULL_STRING_P (reg_info
[reg_no
]) = ret
;
5436 /* If this is an optimized succeed_n for zero times, make the jump. */
5438 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5446 /* Get to the number of times to succeed. */
5448 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5453 EXTRACT_NUMBER_AND_INCR (mcnt
, p1
);
5461 if (!REG_MATCH_NULL_STRING_P (reg_info
[*p1
]))
5469 /* All other opcodes mean we cannot match the empty string. */
5475 } /* common_op_match_null_string_p */
5478 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5479 bytes; nonzero otherwise. */
5482 bcmp_translate (s1
, s2
, len
, translate
)
5483 const char *s1
, *s2
;
5485 RE_TRANSLATE_TYPE translate
;
5487 register const unsigned char *p1
= (const unsigned char *) s1
;
5488 register const unsigned char *p2
= (const unsigned char *) s2
;
5491 if (translate
[*p1
++] != translate
[*p2
++]) return 1;
5497 /* Entry points for GNU code. */
5499 /* re_compile_pattern is the GNU regular expression compiler: it
5500 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5501 Returns 0 if the pattern was valid, otherwise an error string.
5503 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5504 are set in BUFP on entry.
5506 We call regex_compile to do the actual compilation. */
5509 re_compile_pattern (pattern
, length
, bufp
)
5510 const char *pattern
;
5512 struct re_pattern_buffer
*bufp
;
5516 /* GNU code is written to assume at least RE_NREGS registers will be set
5517 (and at least one extra will be -1). */
5518 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5520 /* And GNU code determines whether or not to get register information
5521 by passing null for the REGS argument to re_match, etc., not by
5525 /* Match anchors at newline. */
5526 bufp
->newline_anchor
= 1;
5528 ret
= regex_compile (pattern
, length
, re_syntax_options
, bufp
);
5532 return gettext (re_error_msgid
+ re_error_msgid_idx
[(int) ret
]);
5535 weak_alias (__re_compile_pattern
, re_compile_pattern
)
5538 /* Entry points compatible with 4.2 BSD regex library. We don't define
5539 them unless specifically requested. */
5541 #if defined _REGEX_RE_COMP || defined _LIBC
5543 /* BSD has one and only one pattern buffer. */
5544 static struct re_pattern_buffer re_comp_buf
;
5548 /* Make these definitions weak in libc, so POSIX programs can redefine
5549 these names if they don't use our functions, and still use
5550 regcomp/regexec below without link errors. */
5560 if (!re_comp_buf
.buffer
)
5561 return gettext ("No previous regular expression");
5565 if (!re_comp_buf
.buffer
)
5567 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5568 if (re_comp_buf
.buffer
== NULL
)
5569 return (char *) gettext (re_error_msgid
5570 + re_error_msgid_idx
[(int) REG_ESPACE
]);
5571 re_comp_buf
.allocated
= 200;
5573 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5574 if (re_comp_buf
.fastmap
== NULL
)
5575 return (char *) gettext (re_error_msgid
5576 + re_error_msgid_idx
[(int) REG_ESPACE
]);
5579 /* Since `re_exec' always passes NULL for the `regs' argument, we
5580 don't need to initialize the pattern buffer fields which affect it. */
5582 /* Match anchors at newlines. */
5583 re_comp_buf
.newline_anchor
= 1;
5585 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5590 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5591 return (char *) gettext (re_error_msgid
+ re_error_msgid_idx
[(int) ret
]);
5602 const int len
= strlen (s
);
5604 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5607 #endif /* _REGEX_RE_COMP */
5609 /* POSIX.2 functions. Don't define these for Emacs. */
5613 /* regcomp takes a regular expression as a string and compiles it.
5615 PREG is a regex_t *. We do not expect any fields to be initialized,
5616 since POSIX says we shouldn't. Thus, we set
5618 `buffer' to the compiled pattern;
5619 `used' to the length of the compiled pattern;
5620 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5621 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5622 RE_SYNTAX_POSIX_BASIC;
5623 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5624 `fastmap' to an allocated space for the fastmap;
5625 `fastmap_accurate' to zero;
5626 `re_nsub' to the number of subexpressions in PATTERN.
5628 PATTERN is the address of the pattern string.
5630 CFLAGS is a series of bits which affect compilation.
5632 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5633 use POSIX basic syntax.
5635 If REG_NEWLINE is set, then . and [^...] don't match newline.
5636 Also, regexec will try a match beginning after every newline.
5638 If REG_ICASE is set, then we considers upper- and lowercase
5639 versions of letters to be equivalent when matching.
5641 If REG_NOSUB is set, then when PREG is passed to regexec, that
5642 routine will report only success or failure, and nothing about the
5645 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5646 the return codes and their meanings.) */
5649 regcomp (preg
, pattern
, cflags
)
5651 const char *pattern
;
5656 = (cflags
& REG_EXTENDED
) ?
5657 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5659 /* regex_compile will allocate the space for the compiled pattern. */
5661 preg
->allocated
= 0;
5664 /* Try to allocate space for the fastmap. */
5665 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5667 if (cflags
& REG_ICASE
)
5672 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5673 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5674 if (preg
->translate
== NULL
)
5675 return (int) REG_ESPACE
;
5677 /* Map uppercase characters to corresponding lowercase ones. */
5678 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5679 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
5682 preg
->translate
= NULL
;
5684 /* If REG_NEWLINE is set, newlines are treated differently. */
5685 if (cflags
& REG_NEWLINE
)
5686 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5687 syntax
&= ~RE_DOT_NEWLINE
;
5688 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5689 /* It also changes the matching behavior. */
5690 preg
->newline_anchor
= 1;
5693 preg
->newline_anchor
= 0;
5695 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5697 /* POSIX says a null character in the pattern terminates it, so we
5698 can use strlen here in compiling the pattern. */
5699 ret
= regex_compile (pattern
, strlen (pattern
), syntax
, preg
);
5701 /* POSIX doesn't distinguish between an unmatched open-group and an
5702 unmatched close-group: both are REG_EPAREN. */
5703 if (ret
== REG_ERPAREN
) ret
= REG_EPAREN
;
5705 if (ret
== REG_NOERROR
&& preg
->fastmap
)
5707 /* Compute the fastmap now, since regexec cannot modify the pattern
5709 if (re_compile_fastmap (preg
) == -2)
5711 /* Some error occured while computing the fastmap, just forget
5713 free (preg
->fastmap
);
5714 preg
->fastmap
= NULL
;
5721 weak_alias (__regcomp
, regcomp
)
5725 /* regexec searches for a given pattern, specified by PREG, in the
5728 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5729 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5730 least NMATCH elements, and we set them to the offsets of the
5731 corresponding matched substrings.
5733 EFLAGS specifies `execution flags' which affect matching: if
5734 REG_NOTBOL is set, then ^ does not match at the beginning of the
5735 string; if REG_NOTEOL is set, then $ does not match at the end.
5737 We return 0 if we find a match and REG_NOMATCH if not. */
5740 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5741 const regex_t
*preg
;
5744 regmatch_t pmatch
[];
5748 struct re_registers regs
;
5749 regex_t private_preg
;
5750 int len
= strlen (string
);
5751 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
5753 private_preg
= *preg
;
5755 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5756 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5758 /* The user has told us exactly how many registers to return
5759 information about, via `nmatch'. We have to pass that on to the
5760 matching routines. */
5761 private_preg
.regs_allocated
= REGS_FIXED
;
5765 regs
.num_regs
= nmatch
;
5766 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
5767 if (regs
.start
== NULL
)
5768 return (int) REG_NOMATCH
;
5769 regs
.end
= regs
.start
+ nmatch
;
5772 /* Perform the searching operation. */
5773 ret
= re_search (&private_preg
, string
, len
,
5774 /* start: */ 0, /* range: */ len
,
5775 want_reg_info
? ®s
: (struct re_registers
*) 0);
5777 /* Copy the register information to the POSIX structure. */
5784 for (r
= 0; r
< nmatch
; r
++)
5786 pmatch
[r
].rm_so
= regs
.start
[r
];
5787 pmatch
[r
].rm_eo
= regs
.end
[r
];
5791 /* If we needed the temporary register info, free the space now. */
5795 /* We want zero return to mean success, unlike `re_search'. */
5796 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5799 weak_alias (__regexec
, regexec
)
5803 /* Returns a message corresponding to an error code, ERRCODE, returned
5804 from either regcomp or regexec. We don't use PREG here. */
5807 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5809 const regex_t
*preg
;
5817 || errcode
>= (int) (sizeof (re_error_msgid_idx
)
5818 / sizeof (re_error_msgid_idx
[0])))
5819 /* Only error codes returned by the rest of the code should be passed
5820 to this routine. If we are given anything else, or if other regex
5821 code generates an invalid error code, then the program has a bug.
5822 Dump core so we can fix it. */
5825 msg
= gettext (re_error_msgid
+ re_error_msgid_idx
[errcode
]);
5827 msg_size
= strlen (msg
) + 1; /* Includes the null. */
5829 if (errbuf_size
!= 0)
5831 if (msg_size
> errbuf_size
)
5833 #if defined HAVE_MEMPCPY || defined _LIBC
5834 *((char *) __mempcpy (errbuf
, msg
, errbuf_size
- 1)) = '\0';
5836 memcpy (errbuf
, msg
, errbuf_size
- 1);
5837 errbuf
[errbuf_size
- 1] = 0;
5841 memcpy (errbuf
, msg
, msg_size
);
5847 weak_alias (__regerror
, regerror
)
5851 /* Free dynamically allocated space used by PREG. */
5857 if (preg
->buffer
!= NULL
)
5858 free (preg
->buffer
);
5859 preg
->buffer
= NULL
;
5861 preg
->allocated
= 0;
5864 if (preg
->fastmap
!= NULL
)
5865 free (preg
->fastmap
);
5866 preg
->fastmap
= NULL
;
5867 preg
->fastmap_accurate
= 0;
5869 if (preg
->translate
!= NULL
)
5870 free (preg
->translate
);
5871 preg
->translate
= NULL
;
5874 weak_alias (__regfree
, regfree
)
5877 #endif /* not emacs */