*** empty log message ***
[bpt/emacs.git] / src / regex.c
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
4
5 Copyright (C) 1993,94,95,96,97,98,99,2000 Free Software Foundation, Inc.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
20 USA. */
21
22 /* TODO:
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
29 */
30
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
33 #pragma alloca
34 #endif
35
36 #undef _GNU_SOURCE
37 #define _GNU_SOURCE
38
39 #ifdef HAVE_CONFIG_H
40 # include <config.h>
41 #endif
42
43 #if defined STDC_HEADERS && !defined emacs
44 # include <stddef.h>
45 #else
46 /* We need this for `regex.h', and perhaps for the Emacs include files. */
47 # include <sys/types.h>
48 #endif
49
50 /* Whether to use ISO C Amendment 1 wide char functions.
51 Those should not be used for Emacs since it uses its own. */
52 #if defined _LIBC
53 #define WIDE_CHAR_SUPPORT 1
54 #else
55 #define WIDE_CHAR_SUPPORT \
56 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
57 #endif
58
59 /* For platform which support the ISO C amendement 1 functionality we
60 support user defined character classes. */
61 #if WIDE_CHAR_SUPPORT
62 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
63 # include <wchar.h>
64 # include <wctype.h>
65 #endif
66
67 #ifdef _LIBC
68 /* We have to keep the namespace clean. */
69 # define regfree(preg) __regfree (preg)
70 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
71 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
72 # define regerror(errcode, preg, errbuf, errbuf_size) \
73 __regerror(errcode, preg, errbuf, errbuf_size)
74 # define re_set_registers(bu, re, nu, st, en) \
75 __re_set_registers (bu, re, nu, st, en)
76 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
77 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
78 # define re_match(bufp, string, size, pos, regs) \
79 __re_match (bufp, string, size, pos, regs)
80 # define re_search(bufp, string, size, startpos, range, regs) \
81 __re_search (bufp, string, size, startpos, range, regs)
82 # define re_compile_pattern(pattern, length, bufp) \
83 __re_compile_pattern (pattern, length, bufp)
84 # define re_set_syntax(syntax) __re_set_syntax (syntax)
85 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
86 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
87 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
88
89 /* Make sure we call libc's function even if the user overrides them. */
90 # define btowc __btowc
91 # define iswctype __iswctype
92 # define wctype __wctype
93
94 # define WEAK_ALIAS(a,b) weak_alias (a, b)
95
96 /* We are also using some library internals. */
97 # include <locale/localeinfo.h>
98 # include <locale/elem-hash.h>
99 # include <langinfo.h>
100 #else
101 # define WEAK_ALIAS(a,b)
102 #endif
103
104 /* This is for other GNU distributions with internationalized messages. */
105 #if HAVE_LIBINTL_H || defined _LIBC
106 # include <libintl.h>
107 #else
108 # define gettext(msgid) (msgid)
109 #endif
110
111 #ifndef gettext_noop
112 /* This define is so xgettext can find the internationalizable
113 strings. */
114 # define gettext_noop(String) String
115 #endif
116
117 /* The `emacs' switch turns on certain matching commands
118 that make sense only in Emacs. */
119 #ifdef emacs
120
121 # include "lisp.h"
122 # include "buffer.h"
123
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
126
127 # include "syntax.h"
128 # include "character.h"
129 # include "category.h"
130
131 # ifdef malloc
132 # undef malloc
133 # endif
134 # define malloc xmalloc
135 # ifdef realloc
136 # undef realloc
137 # endif
138 # define realloc xrealloc
139 # ifdef free
140 # undef free
141 # endif
142 # define free xfree
143
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
147
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, s) \
151 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
154
155 /* Set C a (possibly multibyte) character before P. P points into a
156 string which is the virtual concatenation of STR1 (which ends at
157 END1) or STR2 (which ends at END2). */
158 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
159 do { \
160 if (target_multibyte) \
161 { \
162 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
163 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
164 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
165 c = STRING_CHAR (dtemp, (p) - dtemp); \
166 } \
167 else \
168 { \
169 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
170 if (multibyte) \
171 MAKE_CHAR_MULTIBYTE (c); \
172 } \
173 } while (0)
174
175
176 #else /* not emacs */
177
178 /* If we are not linking with Emacs proper,
179 we can't use the relocating allocator
180 even if config.h says that we can. */
181 # undef REL_ALLOC
182
183 # if defined STDC_HEADERS || defined _LIBC
184 # include <stdlib.h>
185 # else
186 char *malloc ();
187 char *realloc ();
188 # endif
189
190 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
191 If nothing else has been done, use the method below. */
192 # ifdef INHIBIT_STRING_HEADER
193 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
194 # if !defined bzero && !defined bcopy
195 # undef INHIBIT_STRING_HEADER
196 # endif
197 # endif
198 # endif
199
200 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
201 This is used in most programs--a few other programs avoid this
202 by defining INHIBIT_STRING_HEADER. */
203 # ifndef INHIBIT_STRING_HEADER
204 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
205 # include <string.h>
206 # ifndef bzero
207 # ifndef _LIBC
208 # define bzero(s, n) (memset (s, '\0', n), (s))
209 # else
210 # define bzero(s, n) __bzero (s, n)
211 # endif
212 # endif
213 # else
214 # include <strings.h>
215 # ifndef memcmp
216 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
217 # endif
218 # ifndef memcpy
219 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
220 # endif
221 # endif
222 # endif
223
224 /* Define the syntax stuff for \<, \>, etc. */
225
226 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
227 enum syntaxcode { Swhitespace = 0, Sword = 1 };
228
229 # ifdef SWITCH_ENUM_BUG
230 # define SWITCH_ENUM_CAST(x) ((int)(x))
231 # else
232 # define SWITCH_ENUM_CAST(x) (x)
233 # endif
234
235 /* Dummy macros for non-Emacs environments. */
236 # define BASE_LEADING_CODE_P(c) (0)
237 # define CHAR_CHARSET(c) 0
238 # define CHARSET_LEADING_CODE_BASE(c) 0
239 # define MAX_MULTIBYTE_LENGTH 1
240 # define RE_MULTIBYTE_P(x) 0
241 # define RE_TARGET_MULTIBYTE_P(x) 0
242 # define WORD_BOUNDARY_P(c1, c2) (0)
243 # define CHAR_HEAD_P(p) (1)
244 # define SINGLE_BYTE_CHAR_P(c) (1)
245 # define SAME_CHARSET_P(c1, c2) (1)
246 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
247 # define STRING_CHAR(p, s) (*(p))
248 # define RE_STRING_CHAR STRING_CHAR
249 # define CHAR_STRING(c, s) (*(s) = (c), 1)
250 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
251 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
252 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
253 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
254 # define MAKE_CHAR(charset, c1, c2) (c1)
255 # define BYTE8_TO_CHAR(c) (c)
256 # define CHAR_BYTE8_P(c) (0)
257 # define MAKE_CHAR_MULTIBYTE(c) 0
258 # define CHAR_LEADING_CODE(c) (c)
259 #endif /* not emacs */
260
261 #ifndef RE_TRANSLATE
262 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
263 # define RE_TRANSLATE_P(TBL) (TBL)
264 #endif
265 \f
266 /* Get the interface, including the syntax bits. */
267 #include "regex.h"
268
269 /* isalpha etc. are used for the character classes. */
270 #include <ctype.h>
271
272 #ifdef emacs
273
274 /* 1 if C is an ASCII character. */
275 # define IS_REAL_ASCII(c) ((c) < 0200)
276
277 /* 1 if C is a unibyte character. */
278 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
279
280 /* The Emacs definitions should not be directly affected by locales. */
281
282 /* In Emacs, these are only used for single-byte characters. */
283 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
284 # define ISCNTRL(c) ((c) < ' ')
285 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
286 || ((c) >= 'a' && (c) <= 'f') \
287 || ((c) >= 'A' && (c) <= 'F'))
288
289 /* This is only used for single-byte characters. */
290 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
291
292 /* The rest must handle multibyte characters. */
293
294 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
295 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
296 : 1)
297
298 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
299 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
300 : 1)
301
302 # define ISALNUM(c) (IS_REAL_ASCII (c) \
303 ? (((c) >= 'a' && (c) <= 'z') \
304 || ((c) >= 'A' && (c) <= 'Z') \
305 || ((c) >= '0' && (c) <= '9')) \
306 : SYNTAX (c) == Sword)
307
308 # define ISALPHA(c) (IS_REAL_ASCII (c) \
309 ? (((c) >= 'a' && (c) <= 'z') \
310 || ((c) >= 'A' && (c) <= 'Z')) \
311 : SYNTAX (c) == Sword)
312
313 # define ISLOWER(c) (LOWERCASEP (c))
314
315 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
316 ? ((c) > ' ' && (c) < 0177 \
317 && !(((c) >= 'a' && (c) <= 'z') \
318 || ((c) >= 'A' && (c) <= 'Z') \
319 || ((c) >= '0' && (c) <= '9'))) \
320 : SYNTAX (c) != Sword)
321
322 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
323
324 # define ISUPPER(c) (UPPERCASEP (c))
325
326 # define ISWORD(c) (SYNTAX (c) == Sword)
327
328 #else /* not emacs */
329
330 /* Jim Meyering writes:
331
332 "... Some ctype macros are valid only for character codes that
333 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
334 using /bin/cc or gcc but without giving an ansi option). So, all
335 ctype uses should be through macros like ISPRINT... If
336 STDC_HEADERS is defined, then autoconf has verified that the ctype
337 macros don't need to be guarded with references to isascii. ...
338 Defining isascii to 1 should let any compiler worth its salt
339 eliminate the && through constant folding."
340 Solaris defines some of these symbols so we must undefine them first. */
341
342 # undef ISASCII
343 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
344 # define ISASCII(c) 1
345 # else
346 # define ISASCII(c) isascii(c)
347 # endif
348
349 /* 1 if C is an ASCII character. */
350 # define IS_REAL_ASCII(c) ((c) < 0200)
351
352 /* This distinction is not meaningful, except in Emacs. */
353 # define ISUNIBYTE(c) 1
354
355 # ifdef isblank
356 # define ISBLANK(c) (ISASCII (c) && isblank (c))
357 # else
358 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
359 # endif
360 # ifdef isgraph
361 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
362 # else
363 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
364 # endif
365
366 # undef ISPRINT
367 # define ISPRINT(c) (ISASCII (c) && isprint (c))
368 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
369 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
370 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
371 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
372 # define ISLOWER(c) (ISASCII (c) && islower (c))
373 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
374 # define ISSPACE(c) (ISASCII (c) && isspace (c))
375 # define ISUPPER(c) (ISASCII (c) && isupper (c))
376 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
377
378 # define ISWORD(c) ISALPHA(c)
379
380 # ifdef _tolower
381 # define TOLOWER(c) _tolower(c)
382 # else
383 # define TOLOWER(c) tolower(c)
384 # endif
385
386 /* How many characters in the character set. */
387 # define CHAR_SET_SIZE 256
388
389 # ifdef SYNTAX_TABLE
390
391 extern char *re_syntax_table;
392
393 # else /* not SYNTAX_TABLE */
394
395 static char re_syntax_table[CHAR_SET_SIZE];
396
397 static void
398 init_syntax_once ()
399 {
400 register int c;
401 static int done = 0;
402
403 if (done)
404 return;
405
406 bzero (re_syntax_table, sizeof re_syntax_table);
407
408 for (c = 0; c < CHAR_SET_SIZE; ++c)
409 if (ISALNUM (c))
410 re_syntax_table[c] = Sword;
411
412 re_syntax_table['_'] = Sword;
413
414 done = 1;
415 }
416
417 # endif /* not SYNTAX_TABLE */
418
419 # define SYNTAX(c) re_syntax_table[(c)]
420
421 #endif /* not emacs */
422 \f
423 #ifndef NULL
424 # define NULL (void *)0
425 #endif
426
427 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
428 since ours (we hope) works properly with all combinations of
429 machines, compilers, `char' and `unsigned char' argument types.
430 (Per Bothner suggested the basic approach.) */
431 #undef SIGN_EXTEND_CHAR
432 #if __STDC__
433 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
434 #else /* not __STDC__ */
435 /* As in Harbison and Steele. */
436 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
437 #endif
438 \f
439 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
440 use `alloca' instead of `malloc'. This is because using malloc in
441 re_search* or re_match* could cause memory leaks when C-g is used in
442 Emacs; also, malloc is slower and causes storage fragmentation. On
443 the other hand, malloc is more portable, and easier to debug.
444
445 Because we sometimes use alloca, some routines have to be macros,
446 not functions -- `alloca'-allocated space disappears at the end of the
447 function it is called in. */
448
449 #ifdef REGEX_MALLOC
450
451 # define REGEX_ALLOCATE malloc
452 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
453 # define REGEX_FREE free
454
455 #else /* not REGEX_MALLOC */
456
457 /* Emacs already defines alloca, sometimes. */
458 # ifndef alloca
459
460 /* Make alloca work the best possible way. */
461 # ifdef __GNUC__
462 # define alloca __builtin_alloca
463 # else /* not __GNUC__ */
464 # ifdef HAVE_ALLOCA_H
465 # include <alloca.h>
466 # endif /* HAVE_ALLOCA_H */
467 # endif /* not __GNUC__ */
468
469 # endif /* not alloca */
470
471 # define REGEX_ALLOCATE alloca
472
473 /* Assumes a `char *destination' variable. */
474 # define REGEX_REALLOCATE(source, osize, nsize) \
475 (destination = (char *) alloca (nsize), \
476 memcpy (destination, source, osize))
477
478 /* No need to do anything to free, after alloca. */
479 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
480
481 #endif /* not REGEX_MALLOC */
482
483 /* Define how to allocate the failure stack. */
484
485 #if defined REL_ALLOC && defined REGEX_MALLOC
486
487 # define REGEX_ALLOCATE_STACK(size) \
488 r_alloc (&failure_stack_ptr, (size))
489 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
490 r_re_alloc (&failure_stack_ptr, (nsize))
491 # define REGEX_FREE_STACK(ptr) \
492 r_alloc_free (&failure_stack_ptr)
493
494 #else /* not using relocating allocator */
495
496 # ifdef REGEX_MALLOC
497
498 # define REGEX_ALLOCATE_STACK malloc
499 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
500 # define REGEX_FREE_STACK free
501
502 # else /* not REGEX_MALLOC */
503
504 # define REGEX_ALLOCATE_STACK alloca
505
506 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
507 REGEX_REALLOCATE (source, osize, nsize)
508 /* No need to explicitly free anything. */
509 # define REGEX_FREE_STACK(arg) ((void)0)
510
511 # endif /* not REGEX_MALLOC */
512 #endif /* not using relocating allocator */
513
514
515 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
516 `string1' or just past its end. This works if PTR is NULL, which is
517 a good thing. */
518 #define FIRST_STRING_P(ptr) \
519 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
520
521 /* (Re)Allocate N items of type T using malloc, or fail. */
522 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
523 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
524 #define RETALLOC_IF(addr, n, t) \
525 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
526 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
527
528 #define BYTEWIDTH 8 /* In bits. */
529
530 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
531
532 #undef MAX
533 #undef MIN
534 #define MAX(a, b) ((a) > (b) ? (a) : (b))
535 #define MIN(a, b) ((a) < (b) ? (a) : (b))
536
537 /* Type of source-pattern and string chars. */
538 typedef const unsigned char re_char;
539
540 typedef char boolean;
541 #define false 0
542 #define true 1
543
544 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
545 re_char *string1, int size1,
546 re_char *string2, int size2,
547 int pos,
548 struct re_registers *regs,
549 int stop));
550 \f
551 /* These are the command codes that appear in compiled regular
552 expressions. Some opcodes are followed by argument bytes. A
553 command code can specify any interpretation whatsoever for its
554 arguments. Zero bytes may appear in the compiled regular expression. */
555
556 typedef enum
557 {
558 no_op = 0,
559
560 /* Succeed right away--no more backtracking. */
561 succeed,
562
563 /* Followed by one byte giving n, then by n literal bytes. */
564 exactn,
565
566 /* Matches any (more or less) character. */
567 anychar,
568
569 /* Matches any one char belonging to specified set. First
570 following byte is number of bitmap bytes. Then come bytes
571 for a bitmap saying which chars are in. Bits in each byte
572 are ordered low-bit-first. A character is in the set if its
573 bit is 1. A character too large to have a bit in the map is
574 automatically not in the set.
575
576 If the length byte has the 0x80 bit set, then that stuff
577 is followed by a range table:
578 2 bytes of flags for character sets (low 8 bits, high 8 bits)
579 See RANGE_TABLE_WORK_BITS below.
580 2 bytes, the number of pairs that follow (upto 32767)
581 pairs, each 2 multibyte characters,
582 each multibyte character represented as 3 bytes. */
583 charset,
584
585 /* Same parameters as charset, but match any character that is
586 not one of those specified. */
587 charset_not,
588
589 /* Start remembering the text that is matched, for storing in a
590 register. Followed by one byte with the register number, in
591 the range 0 to one less than the pattern buffer's re_nsub
592 field. */
593 start_memory,
594
595 /* Stop remembering the text that is matched and store it in a
596 memory register. Followed by one byte with the register
597 number, in the range 0 to one less than `re_nsub' in the
598 pattern buffer. */
599 stop_memory,
600
601 /* Match a duplicate of something remembered. Followed by one
602 byte containing the register number. */
603 duplicate,
604
605 /* Fail unless at beginning of line. */
606 begline,
607
608 /* Fail unless at end of line. */
609 endline,
610
611 /* Succeeds if at beginning of buffer (if emacs) or at beginning
612 of string to be matched (if not). */
613 begbuf,
614
615 /* Analogously, for end of buffer/string. */
616 endbuf,
617
618 /* Followed by two byte relative address to which to jump. */
619 jump,
620
621 /* Followed by two-byte relative address of place to resume at
622 in case of failure. */
623 on_failure_jump,
624
625 /* Like on_failure_jump, but pushes a placeholder instead of the
626 current string position when executed. */
627 on_failure_keep_string_jump,
628
629 /* Just like `on_failure_jump', except that it checks that we
630 don't get stuck in an infinite loop (matching an empty string
631 indefinitely). */
632 on_failure_jump_loop,
633
634 /* Just like `on_failure_jump_loop', except that it checks for
635 a different kind of loop (the kind that shows up with non-greedy
636 operators). This operation has to be immediately preceded
637 by a `no_op'. */
638 on_failure_jump_nastyloop,
639
640 /* A smart `on_failure_jump' used for greedy * and + operators.
641 It analyses the loop before which it is put and if the
642 loop does not require backtracking, it changes itself to
643 `on_failure_keep_string_jump' and short-circuits the loop,
644 else it just defaults to changing itself into `on_failure_jump'.
645 It assumes that it is pointing to just past a `jump'. */
646 on_failure_jump_smart,
647
648 /* Followed by two-byte relative address and two-byte number n.
649 After matching N times, jump to the address upon failure.
650 Does not work if N starts at 0: use on_failure_jump_loop
651 instead. */
652 succeed_n,
653
654 /* Followed by two-byte relative address, and two-byte number n.
655 Jump to the address N times, then fail. */
656 jump_n,
657
658 /* Set the following two-byte relative address to the
659 subsequent two-byte number. The address *includes* the two
660 bytes of number. */
661 set_number_at,
662
663 wordbeg, /* Succeeds if at word beginning. */
664 wordend, /* Succeeds if at word end. */
665
666 wordbound, /* Succeeds if at a word boundary. */
667 notwordbound, /* Succeeds if not at a word boundary. */
668
669 /* Matches any character whose syntax is specified. Followed by
670 a byte which contains a syntax code, e.g., Sword. */
671 syntaxspec,
672
673 /* Matches any character whose syntax is not that specified. */
674 notsyntaxspec
675
676 #ifdef emacs
677 ,before_dot, /* Succeeds if before point. */
678 at_dot, /* Succeeds if at point. */
679 after_dot, /* Succeeds if after point. */
680
681 /* Matches any character whose category-set contains the specified
682 category. The operator is followed by a byte which contains a
683 category code (mnemonic ASCII character). */
684 categoryspec,
685
686 /* Matches any character whose category-set does not contain the
687 specified category. The operator is followed by a byte which
688 contains the category code (mnemonic ASCII character). */
689 notcategoryspec
690 #endif /* emacs */
691 } re_opcode_t;
692 \f
693 /* Common operations on the compiled pattern. */
694
695 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
696
697 #define STORE_NUMBER(destination, number) \
698 do { \
699 (destination)[0] = (number) & 0377; \
700 (destination)[1] = (number) >> 8; \
701 } while (0)
702
703 /* Same as STORE_NUMBER, except increment DESTINATION to
704 the byte after where the number is stored. Therefore, DESTINATION
705 must be an lvalue. */
706
707 #define STORE_NUMBER_AND_INCR(destination, number) \
708 do { \
709 STORE_NUMBER (destination, number); \
710 (destination) += 2; \
711 } while (0)
712
713 /* Put into DESTINATION a number stored in two contiguous bytes starting
714 at SOURCE. */
715
716 #define EXTRACT_NUMBER(destination, source) \
717 do { \
718 (destination) = *(source) & 0377; \
719 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
720 } while (0)
721
722 #ifdef DEBUG
723 static void extract_number _RE_ARGS ((int *dest, re_char *source));
724 static void
725 extract_number (dest, source)
726 int *dest;
727 re_char *source;
728 {
729 int temp = SIGN_EXTEND_CHAR (*(source + 1));
730 *dest = *source & 0377;
731 *dest += temp << 8;
732 }
733
734 # ifndef EXTRACT_MACROS /* To debug the macros. */
735 # undef EXTRACT_NUMBER
736 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
737 # endif /* not EXTRACT_MACROS */
738
739 #endif /* DEBUG */
740
741 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
742 SOURCE must be an lvalue. */
743
744 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
745 do { \
746 EXTRACT_NUMBER (destination, source); \
747 (source) += 2; \
748 } while (0)
749
750 #ifdef DEBUG
751 static void extract_number_and_incr _RE_ARGS ((int *destination,
752 re_char **source));
753 static void
754 extract_number_and_incr (destination, source)
755 int *destination;
756 re_char **source;
757 {
758 extract_number (destination, *source);
759 *source += 2;
760 }
761
762 # ifndef EXTRACT_MACROS
763 # undef EXTRACT_NUMBER_AND_INCR
764 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
765 extract_number_and_incr (&dest, &src)
766 # endif /* not EXTRACT_MACROS */
767
768 #endif /* DEBUG */
769 \f
770 /* Store a multibyte character in three contiguous bytes starting
771 DESTINATION, and increment DESTINATION to the byte after where the
772 character is stored. Therefore, DESTINATION must be an lvalue. */
773
774 #define STORE_CHARACTER_AND_INCR(destination, character) \
775 do { \
776 (destination)[0] = (character) & 0377; \
777 (destination)[1] = ((character) >> 8) & 0377; \
778 (destination)[2] = (character) >> 16; \
779 (destination) += 3; \
780 } while (0)
781
782 /* Put into DESTINATION a character stored in three contiguous bytes
783 starting at SOURCE. */
784
785 #define EXTRACT_CHARACTER(destination, source) \
786 do { \
787 (destination) = ((source)[0] \
788 | ((source)[1] << 8) \
789 | ((source)[2] << 16)); \
790 } while (0)
791
792
793 /* Macros for charset. */
794
795 /* Size of bitmap of charset P in bytes. P is a start of charset,
796 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
797 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
798
799 /* Nonzero if charset P has range table. */
800 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
801
802 /* Return the address of range table of charset P. But not the start
803 of table itself, but the before where the number of ranges is
804 stored. `2 +' means to skip re_opcode_t and size of bitmap,
805 and the 2 bytes of flags at the start of the range table. */
806 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
807
808 /* Extract the bit flags that start a range table. */
809 #define CHARSET_RANGE_TABLE_BITS(p) \
810 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
811 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
812
813 /* Test if C is listed in the bitmap of charset P. */
814 #define CHARSET_LOOKUP_BITMAP(p, c) \
815 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
816 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
817
818 /* Return the address of end of RANGE_TABLE. COUNT is number of
819 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
820 is start of range and end of range. `* 3' is size of each start
821 and end. */
822 #define CHARSET_RANGE_TABLE_END(range_table, count) \
823 ((range_table) + (count) * 2 * 3)
824
825 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
826 COUNT is number of ranges in RANGE_TABLE. */
827 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
828 do \
829 { \
830 re_wchar_t range_start, range_end; \
831 re_char *p; \
832 re_char *range_table_end \
833 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
834 \
835 for (p = (range_table); p < range_table_end; p += 2 * 3) \
836 { \
837 EXTRACT_CHARACTER (range_start, p); \
838 EXTRACT_CHARACTER (range_end, p + 3); \
839 \
840 if (range_start <= (c) && (c) <= range_end) \
841 { \
842 (not) = !(not); \
843 break; \
844 } \
845 } \
846 } \
847 while (0)
848
849 /* Test if C is in range table of CHARSET. The flag NOT is negated if
850 C is listed in it. */
851 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
852 do \
853 { \
854 /* Number of ranges in range table. */ \
855 int count; \
856 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
857 \
858 EXTRACT_NUMBER_AND_INCR (count, range_table); \
859 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
860 } \
861 while (0)
862 \f
863 /* If DEBUG is defined, Regex prints many voluminous messages about what
864 it is doing (if the variable `debug' is nonzero). If linked with the
865 main program in `iregex.c', you can enter patterns and strings
866 interactively. And if linked with the main program in `main.c' and
867 the other test files, you can run the already-written tests. */
868
869 #ifdef DEBUG
870
871 /* We use standard I/O for debugging. */
872 # include <stdio.h>
873
874 /* It is useful to test things that ``must'' be true when debugging. */
875 # include <assert.h>
876
877 static int debug = -100000;
878
879 # define DEBUG_STATEMENT(e) e
880 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
881 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
882 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
883 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
884 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
885 if (debug > 0) print_partial_compiled_pattern (s, e)
886 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
887 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
888
889
890 /* Print the fastmap in human-readable form. */
891
892 void
893 print_fastmap (fastmap)
894 char *fastmap;
895 {
896 unsigned was_a_range = 0;
897 unsigned i = 0;
898
899 while (i < (1 << BYTEWIDTH))
900 {
901 if (fastmap[i++])
902 {
903 was_a_range = 0;
904 putchar (i - 1);
905 while (i < (1 << BYTEWIDTH) && fastmap[i])
906 {
907 was_a_range = 1;
908 i++;
909 }
910 if (was_a_range)
911 {
912 printf ("-");
913 putchar (i - 1);
914 }
915 }
916 }
917 putchar ('\n');
918 }
919
920
921 /* Print a compiled pattern string in human-readable form, starting at
922 the START pointer into it and ending just before the pointer END. */
923
924 void
925 print_partial_compiled_pattern (start, end)
926 re_char *start;
927 re_char *end;
928 {
929 int mcnt, mcnt2;
930 re_char *p = start;
931 re_char *pend = end;
932
933 if (start == NULL)
934 {
935 printf ("(null)\n");
936 return;
937 }
938
939 /* Loop over pattern commands. */
940 while (p < pend)
941 {
942 printf ("%d:\t", p - start);
943
944 switch ((re_opcode_t) *p++)
945 {
946 case no_op:
947 printf ("/no_op");
948 break;
949
950 case succeed:
951 printf ("/succeed");
952 break;
953
954 case exactn:
955 mcnt = *p++;
956 printf ("/exactn/%d", mcnt);
957 do
958 {
959 putchar ('/');
960 putchar (*p++);
961 }
962 while (--mcnt);
963 break;
964
965 case start_memory:
966 printf ("/start_memory/%d", *p++);
967 break;
968
969 case stop_memory:
970 printf ("/stop_memory/%d", *p++);
971 break;
972
973 case duplicate:
974 printf ("/duplicate/%d", *p++);
975 break;
976
977 case anychar:
978 printf ("/anychar");
979 break;
980
981 case charset:
982 case charset_not:
983 {
984 register int c, last = -100;
985 register int in_range = 0;
986 int length = CHARSET_BITMAP_SIZE (p - 1);
987 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
988
989 printf ("/charset [%s",
990 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
991
992 assert (p + *p < pend);
993
994 for (c = 0; c < 256; c++)
995 if (c / 8 < length
996 && (p[1 + (c/8)] & (1 << (c % 8))))
997 {
998 /* Are we starting a range? */
999 if (last + 1 == c && ! in_range)
1000 {
1001 putchar ('-');
1002 in_range = 1;
1003 }
1004 /* Have we broken a range? */
1005 else if (last + 1 != c && in_range)
1006 {
1007 putchar (last);
1008 in_range = 0;
1009 }
1010
1011 if (! in_range)
1012 putchar (c);
1013
1014 last = c;
1015 }
1016
1017 if (in_range)
1018 putchar (last);
1019
1020 putchar (']');
1021
1022 p += 1 + length;
1023
1024 if (has_range_table)
1025 {
1026 int count;
1027 printf ("has-range-table");
1028
1029 /* ??? Should print the range table; for now, just skip it. */
1030 p += 2; /* skip range table bits */
1031 EXTRACT_NUMBER_AND_INCR (count, p);
1032 p = CHARSET_RANGE_TABLE_END (p, count);
1033 }
1034 }
1035 break;
1036
1037 case begline:
1038 printf ("/begline");
1039 break;
1040
1041 case endline:
1042 printf ("/endline");
1043 break;
1044
1045 case on_failure_jump:
1046 extract_number_and_incr (&mcnt, &p);
1047 printf ("/on_failure_jump to %d", p + mcnt - start);
1048 break;
1049
1050 case on_failure_keep_string_jump:
1051 extract_number_and_incr (&mcnt, &p);
1052 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
1053 break;
1054
1055 case on_failure_jump_nastyloop:
1056 extract_number_and_incr (&mcnt, &p);
1057 printf ("/on_failure_jump_nastyloop to %d", p + mcnt - start);
1058 break;
1059
1060 case on_failure_jump_loop:
1061 extract_number_and_incr (&mcnt, &p);
1062 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
1063 break;
1064
1065 case on_failure_jump_smart:
1066 extract_number_and_incr (&mcnt, &p);
1067 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
1068 break;
1069
1070 case jump:
1071 extract_number_and_incr (&mcnt, &p);
1072 printf ("/jump to %d", p + mcnt - start);
1073 break;
1074
1075 case succeed_n:
1076 extract_number_and_incr (&mcnt, &p);
1077 extract_number_and_incr (&mcnt2, &p);
1078 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1079 break;
1080
1081 case jump_n:
1082 extract_number_and_incr (&mcnt, &p);
1083 extract_number_and_incr (&mcnt2, &p);
1084 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1085 break;
1086
1087 case set_number_at:
1088 extract_number_and_incr (&mcnt, &p);
1089 extract_number_and_incr (&mcnt2, &p);
1090 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1091 break;
1092
1093 case wordbound:
1094 printf ("/wordbound");
1095 break;
1096
1097 case notwordbound:
1098 printf ("/notwordbound");
1099 break;
1100
1101 case wordbeg:
1102 printf ("/wordbeg");
1103 break;
1104
1105 case wordend:
1106 printf ("/wordend");
1107
1108 case syntaxspec:
1109 printf ("/syntaxspec");
1110 mcnt = *p++;
1111 printf ("/%d", mcnt);
1112 break;
1113
1114 case notsyntaxspec:
1115 printf ("/notsyntaxspec");
1116 mcnt = *p++;
1117 printf ("/%d", mcnt);
1118 break;
1119
1120 # ifdef emacs
1121 case before_dot:
1122 printf ("/before_dot");
1123 break;
1124
1125 case at_dot:
1126 printf ("/at_dot");
1127 break;
1128
1129 case after_dot:
1130 printf ("/after_dot");
1131 break;
1132
1133 case categoryspec:
1134 printf ("/categoryspec");
1135 mcnt = *p++;
1136 printf ("/%d", mcnt);
1137 break;
1138
1139 case notcategoryspec:
1140 printf ("/notcategoryspec");
1141 mcnt = *p++;
1142 printf ("/%d", mcnt);
1143 break;
1144 # endif /* emacs */
1145
1146 case begbuf:
1147 printf ("/begbuf");
1148 break;
1149
1150 case endbuf:
1151 printf ("/endbuf");
1152 break;
1153
1154 default:
1155 printf ("?%d", *(p-1));
1156 }
1157
1158 putchar ('\n');
1159 }
1160
1161 printf ("%d:\tend of pattern.\n", p - start);
1162 }
1163
1164
1165 void
1166 print_compiled_pattern (bufp)
1167 struct re_pattern_buffer *bufp;
1168 {
1169 re_char *buffer = bufp->buffer;
1170
1171 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1172 printf ("%ld bytes used/%ld bytes allocated.\n",
1173 bufp->used, bufp->allocated);
1174
1175 if (bufp->fastmap_accurate && bufp->fastmap)
1176 {
1177 printf ("fastmap: ");
1178 print_fastmap (bufp->fastmap);
1179 }
1180
1181 printf ("re_nsub: %d\t", bufp->re_nsub);
1182 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1183 printf ("can_be_null: %d\t", bufp->can_be_null);
1184 printf ("no_sub: %d\t", bufp->no_sub);
1185 printf ("not_bol: %d\t", bufp->not_bol);
1186 printf ("not_eol: %d\t", bufp->not_eol);
1187 printf ("syntax: %lx\n", bufp->syntax);
1188 fflush (stdout);
1189 /* Perhaps we should print the translate table? */
1190 }
1191
1192
1193 void
1194 print_double_string (where, string1, size1, string2, size2)
1195 re_char *where;
1196 re_char *string1;
1197 re_char *string2;
1198 int size1;
1199 int size2;
1200 {
1201 int this_char;
1202
1203 if (where == NULL)
1204 printf ("(null)");
1205 else
1206 {
1207 if (FIRST_STRING_P (where))
1208 {
1209 for (this_char = where - string1; this_char < size1; this_char++)
1210 putchar (string1[this_char]);
1211
1212 where = string2;
1213 }
1214
1215 for (this_char = where - string2; this_char < size2; this_char++)
1216 putchar (string2[this_char]);
1217 }
1218 }
1219
1220 #else /* not DEBUG */
1221
1222 # undef assert
1223 # define assert(e)
1224
1225 # define DEBUG_STATEMENT(e)
1226 # define DEBUG_PRINT1(x)
1227 # define DEBUG_PRINT2(x1, x2)
1228 # define DEBUG_PRINT3(x1, x2, x3)
1229 # define DEBUG_PRINT4(x1, x2, x3, x4)
1230 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1231 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1232
1233 #endif /* not DEBUG */
1234 \f
1235 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1236 also be assigned to arbitrarily: each pattern buffer stores its own
1237 syntax, so it can be changed between regex compilations. */
1238 /* This has no initializer because initialized variables in Emacs
1239 become read-only after dumping. */
1240 reg_syntax_t re_syntax_options;
1241
1242
1243 /* Specify the precise syntax of regexps for compilation. This provides
1244 for compatibility for various utilities which historically have
1245 different, incompatible syntaxes.
1246
1247 The argument SYNTAX is a bit mask comprised of the various bits
1248 defined in regex.h. We return the old syntax. */
1249
1250 reg_syntax_t
1251 re_set_syntax (syntax)
1252 reg_syntax_t syntax;
1253 {
1254 reg_syntax_t ret = re_syntax_options;
1255
1256 re_syntax_options = syntax;
1257 return ret;
1258 }
1259 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1260 \f
1261 /* This table gives an error message for each of the error codes listed
1262 in regex.h. Obviously the order here has to be same as there.
1263 POSIX doesn't require that we do anything for REG_NOERROR,
1264 but why not be nice? */
1265
1266 static const char *re_error_msgid[] =
1267 {
1268 gettext_noop ("Success"), /* REG_NOERROR */
1269 gettext_noop ("No match"), /* REG_NOMATCH */
1270 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1271 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1272 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1273 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1274 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1275 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1276 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1277 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1278 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1279 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1280 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1281 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1282 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1283 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1284 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1285 };
1286 \f
1287 /* Avoiding alloca during matching, to placate r_alloc. */
1288
1289 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1290 searching and matching functions should not call alloca. On some
1291 systems, alloca is implemented in terms of malloc, and if we're
1292 using the relocating allocator routines, then malloc could cause a
1293 relocation, which might (if the strings being searched are in the
1294 ralloc heap) shift the data out from underneath the regexp
1295 routines.
1296
1297 Here's another reason to avoid allocation: Emacs
1298 processes input from X in a signal handler; processing X input may
1299 call malloc; if input arrives while a matching routine is calling
1300 malloc, then we're scrod. But Emacs can't just block input while
1301 calling matching routines; then we don't notice interrupts when
1302 they come in. So, Emacs blocks input around all regexp calls
1303 except the matching calls, which it leaves unprotected, in the
1304 faith that they will not malloc. */
1305
1306 /* Normally, this is fine. */
1307 #define MATCH_MAY_ALLOCATE
1308
1309 /* When using GNU C, we are not REALLY using the C alloca, no matter
1310 what config.h may say. So don't take precautions for it. */
1311 #ifdef __GNUC__
1312 # undef C_ALLOCA
1313 #endif
1314
1315 /* The match routines may not allocate if (1) they would do it with malloc
1316 and (2) it's not safe for them to use malloc.
1317 Note that if REL_ALLOC is defined, matching would not use malloc for the
1318 failure stack, but we would still use it for the register vectors;
1319 so REL_ALLOC should not affect this. */
1320 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1321 # undef MATCH_MAY_ALLOCATE
1322 #endif
1323
1324 \f
1325 /* Failure stack declarations and macros; both re_compile_fastmap and
1326 re_match_2 use a failure stack. These have to be macros because of
1327 REGEX_ALLOCATE_STACK. */
1328
1329
1330 /* Approximate number of failure points for which to initially allocate space
1331 when matching. If this number is exceeded, we allocate more
1332 space, so it is not a hard limit. */
1333 #ifndef INIT_FAILURE_ALLOC
1334 # define INIT_FAILURE_ALLOC 20
1335 #endif
1336
1337 /* Roughly the maximum number of failure points on the stack. Would be
1338 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1339 This is a variable only so users of regex can assign to it; we never
1340 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1341 before using it, so it should probably be a byte-count instead. */
1342 # if defined MATCH_MAY_ALLOCATE
1343 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1344 whose default stack limit is 2mb. In order for a larger
1345 value to work reliably, you have to try to make it accord
1346 with the process stack limit. */
1347 size_t re_max_failures = 40000;
1348 # else
1349 size_t re_max_failures = 4000;
1350 # endif
1351
1352 union fail_stack_elt
1353 {
1354 re_char *pointer;
1355 /* This should be the biggest `int' that's no bigger than a pointer. */
1356 long integer;
1357 };
1358
1359 typedef union fail_stack_elt fail_stack_elt_t;
1360
1361 typedef struct
1362 {
1363 fail_stack_elt_t *stack;
1364 size_t size;
1365 size_t avail; /* Offset of next open position. */
1366 size_t frame; /* Offset of the cur constructed frame. */
1367 } fail_stack_type;
1368
1369 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1370 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1371
1372
1373 /* Define macros to initialize and free the failure stack.
1374 Do `return -2' if the alloc fails. */
1375
1376 #ifdef MATCH_MAY_ALLOCATE
1377 # define INIT_FAIL_STACK() \
1378 do { \
1379 fail_stack.stack = (fail_stack_elt_t *) \
1380 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1381 * sizeof (fail_stack_elt_t)); \
1382 \
1383 if (fail_stack.stack == NULL) \
1384 return -2; \
1385 \
1386 fail_stack.size = INIT_FAILURE_ALLOC; \
1387 fail_stack.avail = 0; \
1388 fail_stack.frame = 0; \
1389 } while (0)
1390
1391 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1392 #else
1393 # define INIT_FAIL_STACK() \
1394 do { \
1395 fail_stack.avail = 0; \
1396 fail_stack.frame = 0; \
1397 } while (0)
1398
1399 # define RESET_FAIL_STACK() ((void)0)
1400 #endif
1401
1402
1403 /* Double the size of FAIL_STACK, up to a limit
1404 which allows approximately `re_max_failures' items.
1405
1406 Return 1 if succeeds, and 0 if either ran out of memory
1407 allocating space for it or it was already too large.
1408
1409 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1410
1411 /* Factor to increase the failure stack size by
1412 when we increase it.
1413 This used to be 2, but 2 was too wasteful
1414 because the old discarded stacks added up to as much space
1415 were as ultimate, maximum-size stack. */
1416 #define FAIL_STACK_GROWTH_FACTOR 4
1417
1418 #define GROW_FAIL_STACK(fail_stack) \
1419 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1420 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1421 ? 0 \
1422 : ((fail_stack).stack \
1423 = (fail_stack_elt_t *) \
1424 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1425 (fail_stack).size * sizeof (fail_stack_elt_t), \
1426 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1427 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1428 * FAIL_STACK_GROWTH_FACTOR))), \
1429 \
1430 (fail_stack).stack == NULL \
1431 ? 0 \
1432 : ((fail_stack).size \
1433 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1434 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1435 * FAIL_STACK_GROWTH_FACTOR)) \
1436 / sizeof (fail_stack_elt_t)), \
1437 1)))
1438
1439
1440 /* Push a pointer value onto the failure stack.
1441 Assumes the variable `fail_stack'. Probably should only
1442 be called from within `PUSH_FAILURE_POINT'. */
1443 #define PUSH_FAILURE_POINTER(item) \
1444 fail_stack.stack[fail_stack.avail++].pointer = (item)
1445
1446 /* This pushes an integer-valued item onto the failure stack.
1447 Assumes the variable `fail_stack'. Probably should only
1448 be called from within `PUSH_FAILURE_POINT'. */
1449 #define PUSH_FAILURE_INT(item) \
1450 fail_stack.stack[fail_stack.avail++].integer = (item)
1451
1452 /* Push a fail_stack_elt_t value onto the failure stack.
1453 Assumes the variable `fail_stack'. Probably should only
1454 be called from within `PUSH_FAILURE_POINT'. */
1455 #define PUSH_FAILURE_ELT(item) \
1456 fail_stack.stack[fail_stack.avail++] = (item)
1457
1458 /* These three POP... operations complement the three PUSH... operations.
1459 All assume that `fail_stack' is nonempty. */
1460 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1461 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1462 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1463
1464 /* Individual items aside from the registers. */
1465 #define NUM_NONREG_ITEMS 3
1466
1467 /* Used to examine the stack (to detect infinite loops). */
1468 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1469 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1470 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1471 #define TOP_FAILURE_HANDLE() fail_stack.frame
1472
1473
1474 #define ENSURE_FAIL_STACK(space) \
1475 while (REMAINING_AVAIL_SLOTS <= space) { \
1476 if (!GROW_FAIL_STACK (fail_stack)) \
1477 return -2; \
1478 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1479 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1480 }
1481
1482 /* Push register NUM onto the stack. */
1483 #define PUSH_FAILURE_REG(num) \
1484 do { \
1485 char *destination; \
1486 ENSURE_FAIL_STACK(3); \
1487 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1488 num, regstart[num], regend[num]); \
1489 PUSH_FAILURE_POINTER (regstart[num]); \
1490 PUSH_FAILURE_POINTER (regend[num]); \
1491 PUSH_FAILURE_INT (num); \
1492 } while (0)
1493
1494 /* Change the counter's value to VAL, but make sure that it will
1495 be reset when backtracking. */
1496 #define PUSH_NUMBER(ptr,val) \
1497 do { \
1498 char *destination; \
1499 int c; \
1500 ENSURE_FAIL_STACK(3); \
1501 EXTRACT_NUMBER (c, ptr); \
1502 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1503 PUSH_FAILURE_INT (c); \
1504 PUSH_FAILURE_POINTER (ptr); \
1505 PUSH_FAILURE_INT (-1); \
1506 STORE_NUMBER (ptr, val); \
1507 } while (0)
1508
1509 /* Pop a saved register off the stack. */
1510 #define POP_FAILURE_REG_OR_COUNT() \
1511 do { \
1512 int reg = POP_FAILURE_INT (); \
1513 if (reg == -1) \
1514 { \
1515 /* It's a counter. */ \
1516 /* Here, we discard `const', making re_match non-reentrant. */ \
1517 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1518 reg = POP_FAILURE_INT (); \
1519 STORE_NUMBER (ptr, reg); \
1520 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1521 } \
1522 else \
1523 { \
1524 regend[reg] = POP_FAILURE_POINTER (); \
1525 regstart[reg] = POP_FAILURE_POINTER (); \
1526 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1527 reg, regstart[reg], regend[reg]); \
1528 } \
1529 } while (0)
1530
1531 /* Check that we are not stuck in an infinite loop. */
1532 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1533 do { \
1534 int failure = TOP_FAILURE_HANDLE(); \
1535 /* Check for infinite matching loops */ \
1536 while (failure > 0 && \
1537 (FAILURE_STR (failure) == string_place \
1538 || FAILURE_STR (failure) == NULL)) \
1539 { \
1540 assert (FAILURE_PAT (failure) >= bufp->buffer \
1541 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1542 if (FAILURE_PAT (failure) == pat_cur) \
1543 goto fail; \
1544 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1545 failure = NEXT_FAILURE_HANDLE(failure); \
1546 } \
1547 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1548 } while (0)
1549
1550 /* Push the information about the state we will need
1551 if we ever fail back to it.
1552
1553 Requires variables fail_stack, regstart, regend and
1554 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1555 declared.
1556
1557 Does `return FAILURE_CODE' if runs out of memory. */
1558
1559 #define PUSH_FAILURE_POINT(pattern, string_place) \
1560 do { \
1561 char *destination; \
1562 /* Must be int, so when we don't save any registers, the arithmetic \
1563 of 0 + -1 isn't done as unsigned. */ \
1564 \
1565 DEBUG_STATEMENT (nfailure_points_pushed++); \
1566 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1567 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1568 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1569 \
1570 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1571 \
1572 DEBUG_PRINT1 ("\n"); \
1573 \
1574 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1575 PUSH_FAILURE_INT (fail_stack.frame); \
1576 \
1577 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1578 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1579 DEBUG_PRINT1 ("'\n"); \
1580 PUSH_FAILURE_POINTER (string_place); \
1581 \
1582 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1583 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1584 PUSH_FAILURE_POINTER (pattern); \
1585 \
1586 /* Close the frame by moving the frame pointer past it. */ \
1587 fail_stack.frame = fail_stack.avail; \
1588 } while (0)
1589
1590 /* Estimate the size of data pushed by a typical failure stack entry.
1591 An estimate is all we need, because all we use this for
1592 is to choose a limit for how big to make the failure stack. */
1593 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1594 #define TYPICAL_FAILURE_SIZE 20
1595
1596 /* How many items can still be added to the stack without overflowing it. */
1597 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1598
1599
1600 /* Pops what PUSH_FAIL_STACK pushes.
1601
1602 We restore into the parameters, all of which should be lvalues:
1603 STR -- the saved data position.
1604 PAT -- the saved pattern position.
1605 REGSTART, REGEND -- arrays of string positions.
1606
1607 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1608 `pend', `string1', `size1', `string2', and `size2'. */
1609
1610 #define POP_FAILURE_POINT(str, pat) \
1611 do { \
1612 assert (!FAIL_STACK_EMPTY ()); \
1613 \
1614 /* Remove failure points and point to how many regs pushed. */ \
1615 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1616 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1617 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1618 \
1619 /* Pop the saved registers. */ \
1620 while (fail_stack.frame < fail_stack.avail) \
1621 POP_FAILURE_REG_OR_COUNT (); \
1622 \
1623 pat = POP_FAILURE_POINTER (); \
1624 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1625 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1626 \
1627 /* If the saved string location is NULL, it came from an \
1628 on_failure_keep_string_jump opcode, and we want to throw away the \
1629 saved NULL, thus retaining our current position in the string. */ \
1630 str = POP_FAILURE_POINTER (); \
1631 DEBUG_PRINT2 (" Popping string %p: `", str); \
1632 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1633 DEBUG_PRINT1 ("'\n"); \
1634 \
1635 fail_stack.frame = POP_FAILURE_INT (); \
1636 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1637 \
1638 assert (fail_stack.avail >= 0); \
1639 assert (fail_stack.frame <= fail_stack.avail); \
1640 \
1641 DEBUG_STATEMENT (nfailure_points_popped++); \
1642 } while (0) /* POP_FAILURE_POINT */
1643
1644
1645 \f
1646 /* Registers are set to a sentinel when they haven't yet matched. */
1647 #define REG_UNSET(e) ((e) == NULL)
1648 \f
1649 /* Subroutine declarations and macros for regex_compile. */
1650
1651 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1652 reg_syntax_t syntax,
1653 struct re_pattern_buffer *bufp));
1654 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1655 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1656 int arg1, int arg2));
1657 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1658 int arg, unsigned char *end));
1659 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1660 int arg1, int arg2, unsigned char *end));
1661 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1662 re_char *p,
1663 reg_syntax_t syntax));
1664 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1665 re_char *pend,
1666 reg_syntax_t syntax));
1667 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1668 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1669 char *fastmap, const int multibyte));
1670
1671 /* Fetch the next character in the uncompiled pattern---translating it
1672 if necessary. */
1673 #define PATFETCH(c) \
1674 do { \
1675 PATFETCH_RAW (c); \
1676 if (! multibyte) \
1677 MAKE_CHAR_MULTIBYTE (c); \
1678 c = TRANSLATE (c); \
1679 } while (0)
1680
1681 /* Fetch the next character in the uncompiled pattern, with no
1682 translation. */
1683 #define PATFETCH_RAW(c) \
1684 do { \
1685 int len; \
1686 if (p == pend) return REG_EEND; \
1687 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1688 p += len; \
1689 } while (0)
1690
1691
1692 /* If `translate' is non-null, return translate[D], else just D. We
1693 cast the subscript to translate because some data is declared as
1694 `char *', to avoid warnings when a string constant is passed. But
1695 when we use a character as a subscript we must make it unsigned. */
1696 #ifndef TRANSLATE
1697 # define TRANSLATE(d) \
1698 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1699 #endif
1700
1701
1702 /* Macros for outputting the compiled pattern into `buffer'. */
1703
1704 /* If the buffer isn't allocated when it comes in, use this. */
1705 #define INIT_BUF_SIZE 32
1706
1707 /* Make sure we have at least N more bytes of space in buffer. */
1708 #define GET_BUFFER_SPACE(n) \
1709 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1710 EXTEND_BUFFER ()
1711
1712 /* Make sure we have one more byte of buffer space and then add C to it. */
1713 #define BUF_PUSH(c) \
1714 do { \
1715 GET_BUFFER_SPACE (1); \
1716 *b++ = (unsigned char) (c); \
1717 } while (0)
1718
1719
1720 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1721 #define BUF_PUSH_2(c1, c2) \
1722 do { \
1723 GET_BUFFER_SPACE (2); \
1724 *b++ = (unsigned char) (c1); \
1725 *b++ = (unsigned char) (c2); \
1726 } while (0)
1727
1728
1729 /* As with BUF_PUSH_2, except for three bytes. */
1730 #define BUF_PUSH_3(c1, c2, c3) \
1731 do { \
1732 GET_BUFFER_SPACE (3); \
1733 *b++ = (unsigned char) (c1); \
1734 *b++ = (unsigned char) (c2); \
1735 *b++ = (unsigned char) (c3); \
1736 } while (0)
1737
1738
1739 /* Store a jump with opcode OP at LOC to location TO. We store a
1740 relative address offset by the three bytes the jump itself occupies. */
1741 #define STORE_JUMP(op, loc, to) \
1742 store_op1 (op, loc, (to) - (loc) - 3)
1743
1744 /* Likewise, for a two-argument jump. */
1745 #define STORE_JUMP2(op, loc, to, arg) \
1746 store_op2 (op, loc, (to) - (loc) - 3, arg)
1747
1748 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1749 #define INSERT_JUMP(op, loc, to) \
1750 insert_op1 (op, loc, (to) - (loc) - 3, b)
1751
1752 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1753 #define INSERT_JUMP2(op, loc, to, arg) \
1754 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1755
1756
1757 /* This is not an arbitrary limit: the arguments which represent offsets
1758 into the pattern are two bytes long. So if 2^16 bytes turns out to
1759 be too small, many things would have to change. */
1760 /* Any other compiler which, like MSC, has allocation limit below 2^16
1761 bytes will have to use approach similar to what was done below for
1762 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1763 reallocating to 0 bytes. Such thing is not going to work too well.
1764 You have been warned!! */
1765 #if defined _MSC_VER && !defined WIN32
1766 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1767 # define MAX_BUF_SIZE 65500L
1768 #else
1769 # define MAX_BUF_SIZE (1L << 16)
1770 #endif
1771
1772 /* Extend the buffer by twice its current size via realloc and
1773 reset the pointers that pointed into the old block to point to the
1774 correct places in the new one. If extending the buffer results in it
1775 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1776 #if __BOUNDED_POINTERS__
1777 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1778 # define MOVE_BUFFER_POINTER(P) \
1779 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1780 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1781 else \
1782 { \
1783 SET_HIGH_BOUND (b); \
1784 SET_HIGH_BOUND (begalt); \
1785 if (fixup_alt_jump) \
1786 SET_HIGH_BOUND (fixup_alt_jump); \
1787 if (laststart) \
1788 SET_HIGH_BOUND (laststart); \
1789 if (pending_exact) \
1790 SET_HIGH_BOUND (pending_exact); \
1791 }
1792 #else
1793 # define MOVE_BUFFER_POINTER(P) (P) += incr
1794 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1795 #endif
1796 #define EXTEND_BUFFER() \
1797 do { \
1798 re_char *old_buffer = bufp->buffer; \
1799 if (bufp->allocated == MAX_BUF_SIZE) \
1800 return REG_ESIZE; \
1801 bufp->allocated <<= 1; \
1802 if (bufp->allocated > MAX_BUF_SIZE) \
1803 bufp->allocated = MAX_BUF_SIZE; \
1804 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1805 if (bufp->buffer == NULL) \
1806 return REG_ESPACE; \
1807 /* If the buffer moved, move all the pointers into it. */ \
1808 if (old_buffer != bufp->buffer) \
1809 { \
1810 int incr = bufp->buffer - old_buffer; \
1811 MOVE_BUFFER_POINTER (b); \
1812 MOVE_BUFFER_POINTER (begalt); \
1813 if (fixup_alt_jump) \
1814 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1815 if (laststart) \
1816 MOVE_BUFFER_POINTER (laststart); \
1817 if (pending_exact) \
1818 MOVE_BUFFER_POINTER (pending_exact); \
1819 } \
1820 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1821 } while (0)
1822
1823
1824 /* Since we have one byte reserved for the register number argument to
1825 {start,stop}_memory, the maximum number of groups we can report
1826 things about is what fits in that byte. */
1827 #define MAX_REGNUM 255
1828
1829 /* But patterns can have more than `MAX_REGNUM' registers. We just
1830 ignore the excess. */
1831 typedef unsigned regnum_t;
1832
1833
1834 /* Macros for the compile stack. */
1835
1836 /* Since offsets can go either forwards or backwards, this type needs to
1837 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1838 /* int may be not enough when sizeof(int) == 2. */
1839 typedef long pattern_offset_t;
1840
1841 typedef struct
1842 {
1843 pattern_offset_t begalt_offset;
1844 pattern_offset_t fixup_alt_jump;
1845 pattern_offset_t laststart_offset;
1846 regnum_t regnum;
1847 } compile_stack_elt_t;
1848
1849
1850 typedef struct
1851 {
1852 compile_stack_elt_t *stack;
1853 unsigned size;
1854 unsigned avail; /* Offset of next open position. */
1855 } compile_stack_type;
1856
1857
1858 #define INIT_COMPILE_STACK_SIZE 32
1859
1860 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1861 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1862
1863 /* The next available element. */
1864 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1865
1866
1867 /* Structure to manage work area for range table. */
1868 struct range_table_work_area
1869 {
1870 int *table; /* actual work area. */
1871 int allocated; /* allocated size for work area in bytes. */
1872 int used; /* actually used size in words. */
1873 int bits; /* flag to record character classes */
1874 };
1875
1876 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1877 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1878 do { \
1879 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1880 { \
1881 (work_area).allocated += 16 * sizeof (int); \
1882 if ((work_area).table) \
1883 (work_area).table \
1884 = (int *) realloc ((work_area).table, (work_area).allocated); \
1885 else \
1886 (work_area).table \
1887 = (int *) malloc ((work_area).allocated); \
1888 if ((work_area).table == 0) \
1889 FREE_STACK_RETURN (REG_ESPACE); \
1890 } \
1891 } while (0)
1892
1893 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1894 (work_area).bits |= (bit)
1895
1896 /* Bits used to implement the multibyte-part of the various character classes
1897 such as [:alnum:] in a charset's range table. */
1898 #define BIT_WORD 0x1
1899 #define BIT_LOWER 0x2
1900 #define BIT_PUNCT 0x4
1901 #define BIT_SPACE 0x8
1902 #define BIT_UPPER 0x10
1903 #define BIT_MULTIBYTE 0x20
1904
1905 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1906 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1907 do { \
1908 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1909 (work_area).table[(work_area).used++] = (range_start); \
1910 (work_area).table[(work_area).used++] = (range_end); \
1911 } while (0)
1912
1913 /* Free allocated memory for WORK_AREA. */
1914 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1915 do { \
1916 if ((work_area).table) \
1917 free ((work_area).table); \
1918 } while (0)
1919
1920 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1921 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1922 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1923 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1924
1925
1926 /* Set the bit for character C in a list. */
1927 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1928
1929
1930 #ifdef emacs
1931
1932 /* It is better to implement this jumbo macro by a function, but it's
1933 not that easy because macros called within it assumes various
1934 variables being defined. */
1935
1936 #define HANDLE_UNIBYTE_RANGE(work_area, c1, c2) \
1937 do { \
1938 int char_table[257]; \
1939 int i, j, c; \
1940 \
1941 char_table[(c1) - 1] = -2; /* head sentinel */ \
1942 for (i = (c1); i <= (c2); i++) \
1943 char_table[i] = TRANSLATE (unibyte_char_to_multibyte (i)); \
1944 char_table[i] = MAX_CHAR + 2; /* tail sentinel */ \
1945 \
1946 /* As the number of data is small (at most 128) and we can expect \
1947 that data in char_table are mostly sorted, we use fairly simple \
1948 `insertion sort'. */ \
1949 for (i = (c1) + 1; i <= (c2); i++) \
1950 { \
1951 c = char_table[i]; \
1952 j = i; \
1953 while (char_table[j - 1] > c) \
1954 char_table[j] = char_table[j - 1], j--; \
1955 char_table[j] = c; \
1956 } \
1957 \
1958 for (i = (c1); i <= (c2); i++) \
1959 { \
1960 c = char_table[i]; \
1961 if (! IS_REAL_ASCII (c)) \
1962 break; \
1963 SET_LIST_BIT (c); \
1964 } \
1965 while (i <= (c2)) \
1966 { \
1967 c = char_table[i]; \
1968 for (j = i + 1; j <= (c2); j++) \
1969 if (char_table[j] - c != j - i) \
1970 break; \
1971 SET_RANGE_TABLE_WORK_AREA ((work_area), c, char_table[j - 1]); \
1972 i = j; \
1973 } \
1974 } while (0)
1975
1976 #endif /* emacs */
1977
1978 /* Get the next unsigned number in the uncompiled pattern. */
1979 #define GET_UNSIGNED_NUMBER(num) \
1980 do { if (p != pend) \
1981 { \
1982 PATFETCH (c); \
1983 while ('0' <= c && c <= '9') \
1984 { \
1985 if (num < 0) \
1986 num = 0; \
1987 num = num * 10 + c - '0'; \
1988 if (p == pend) \
1989 break; \
1990 PATFETCH (c); \
1991 } \
1992 } \
1993 } while (0)
1994
1995 #if WIDE_CHAR_SUPPORT
1996 /* The GNU C library provides support for user-defined character classes
1997 and the functions from ISO C amendement 1. */
1998 # ifdef CHARCLASS_NAME_MAX
1999 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2000 # else
2001 /* This shouldn't happen but some implementation might still have this
2002 problem. Use a reasonable default value. */
2003 # define CHAR_CLASS_MAX_LENGTH 256
2004 # endif
2005 typedef wctype_t re_wctype_t;
2006 typedef wchar_t re_wchar_t;
2007 # define re_wctype wctype
2008 # define re_iswctype iswctype
2009 # define re_wctype_to_bit(cc) 0
2010 #else
2011 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
2012 # define btowc(c) c
2013
2014 /* Character classes. */
2015 typedef enum { RECC_ERROR = 0,
2016 RECC_ALNUM, RECC_ALPHA, RECC_WORD,
2017 RECC_GRAPH, RECC_PRINT,
2018 RECC_LOWER, RECC_UPPER,
2019 RECC_PUNCT, RECC_CNTRL,
2020 RECC_DIGIT, RECC_XDIGIT,
2021 RECC_BLANK, RECC_SPACE,
2022 RECC_MULTIBYTE, RECC_NONASCII,
2023 RECC_ASCII, RECC_UNIBYTE
2024 } re_wctype_t;
2025
2026 typedef int re_wchar_t;
2027
2028 /* Map a string to the char class it names (if any). */
2029 static re_wctype_t
2030 re_wctype (str)
2031 re_char *str;
2032 {
2033 const char *string = str;
2034 if (STREQ (string, "alnum")) return RECC_ALNUM;
2035 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2036 else if (STREQ (string, "word")) return RECC_WORD;
2037 else if (STREQ (string, "ascii")) return RECC_ASCII;
2038 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2039 else if (STREQ (string, "graph")) return RECC_GRAPH;
2040 else if (STREQ (string, "lower")) return RECC_LOWER;
2041 else if (STREQ (string, "print")) return RECC_PRINT;
2042 else if (STREQ (string, "punct")) return RECC_PUNCT;
2043 else if (STREQ (string, "space")) return RECC_SPACE;
2044 else if (STREQ (string, "upper")) return RECC_UPPER;
2045 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2046 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2047 else if (STREQ (string, "digit")) return RECC_DIGIT;
2048 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2049 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2050 else if (STREQ (string, "blank")) return RECC_BLANK;
2051 else return 0;
2052 }
2053
2054 /* True iff CH is in the char class CC. */
2055 static boolean
2056 re_iswctype (ch, cc)
2057 int ch;
2058 re_wctype_t cc;
2059 {
2060 switch (cc)
2061 {
2062 case RECC_ALNUM: return ISALNUM (ch);
2063 case RECC_ALPHA: return ISALPHA (ch);
2064 case RECC_BLANK: return ISBLANK (ch);
2065 case RECC_CNTRL: return ISCNTRL (ch);
2066 case RECC_DIGIT: return ISDIGIT (ch);
2067 case RECC_GRAPH: return ISGRAPH (ch);
2068 case RECC_LOWER: return ISLOWER (ch);
2069 case RECC_PRINT: return ISPRINT (ch);
2070 case RECC_PUNCT: return ISPUNCT (ch);
2071 case RECC_SPACE: return ISSPACE (ch);
2072 case RECC_UPPER: return ISUPPER (ch);
2073 case RECC_XDIGIT: return ISXDIGIT (ch);
2074 case RECC_ASCII: return IS_REAL_ASCII (ch);
2075 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2076 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2077 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2078 case RECC_WORD: return ISWORD (ch);
2079 case RECC_ERROR: return false;
2080 default:
2081 abort();
2082 }
2083 }
2084
2085 /* Return a bit-pattern to use in the range-table bits to match multibyte
2086 chars of class CC. */
2087 static int
2088 re_wctype_to_bit (cc)
2089 re_wctype_t cc;
2090 {
2091 switch (cc)
2092 {
2093 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2094 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2095 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2096 case RECC_LOWER: return BIT_LOWER;
2097 case RECC_UPPER: return BIT_UPPER;
2098 case RECC_PUNCT: return BIT_PUNCT;
2099 case RECC_SPACE: return BIT_SPACE;
2100 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2101 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2102 default:
2103 abort();
2104 }
2105 }
2106 #endif
2107
2108 /* Explicit quit checking is only used on NTemacs. */
2109 #if defined WINDOWSNT && defined emacs && defined QUIT
2110 extern int immediate_quit;
2111 # define IMMEDIATE_QUIT_CHECK \
2112 do { \
2113 if (immediate_quit) QUIT; \
2114 } while (0)
2115 #else
2116 # define IMMEDIATE_QUIT_CHECK ((void)0)
2117 #endif
2118 \f
2119 #ifndef MATCH_MAY_ALLOCATE
2120
2121 /* If we cannot allocate large objects within re_match_2_internal,
2122 we make the fail stack and register vectors global.
2123 The fail stack, we grow to the maximum size when a regexp
2124 is compiled.
2125 The register vectors, we adjust in size each time we
2126 compile a regexp, according to the number of registers it needs. */
2127
2128 static fail_stack_type fail_stack;
2129
2130 /* Size with which the following vectors are currently allocated.
2131 That is so we can make them bigger as needed,
2132 but never make them smaller. */
2133 static int regs_allocated_size;
2134
2135 static re_char ** regstart, ** regend;
2136 static re_char **best_regstart, **best_regend;
2137
2138 /* Make the register vectors big enough for NUM_REGS registers,
2139 but don't make them smaller. */
2140
2141 static
2142 regex_grow_registers (num_regs)
2143 int num_regs;
2144 {
2145 if (num_regs > regs_allocated_size)
2146 {
2147 RETALLOC_IF (regstart, num_regs, re_char *);
2148 RETALLOC_IF (regend, num_regs, re_char *);
2149 RETALLOC_IF (best_regstart, num_regs, re_char *);
2150 RETALLOC_IF (best_regend, num_regs, re_char *);
2151
2152 regs_allocated_size = num_regs;
2153 }
2154 }
2155
2156 #endif /* not MATCH_MAY_ALLOCATE */
2157 \f
2158 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2159 compile_stack,
2160 regnum_t regnum));
2161
2162 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2163 Returns one of error codes defined in `regex.h', or zero for success.
2164
2165 Assumes the `allocated' (and perhaps `buffer') and `translate'
2166 fields are set in BUFP on entry.
2167
2168 If it succeeds, results are put in BUFP (if it returns an error, the
2169 contents of BUFP are undefined):
2170 `buffer' is the compiled pattern;
2171 `syntax' is set to SYNTAX;
2172 `used' is set to the length of the compiled pattern;
2173 `fastmap_accurate' is zero;
2174 `re_nsub' is the number of subexpressions in PATTERN;
2175 `not_bol' and `not_eol' are zero;
2176
2177 The `fastmap' field is neither examined nor set. */
2178
2179 /* Insert the `jump' from the end of last alternative to "here".
2180 The space for the jump has already been allocated. */
2181 #define FIXUP_ALT_JUMP() \
2182 do { \
2183 if (fixup_alt_jump) \
2184 STORE_JUMP (jump, fixup_alt_jump, b); \
2185 } while (0)
2186
2187
2188 /* Return, freeing storage we allocated. */
2189 #define FREE_STACK_RETURN(value) \
2190 do { \
2191 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2192 free (compile_stack.stack); \
2193 return value; \
2194 } while (0)
2195
2196 static reg_errcode_t
2197 regex_compile (pattern, size, syntax, bufp)
2198 re_char *pattern;
2199 size_t size;
2200 reg_syntax_t syntax;
2201 struct re_pattern_buffer *bufp;
2202 {
2203 /* We fetch characters from PATTERN here. */
2204 register re_wchar_t c, c1;
2205
2206 /* A random temporary spot in PATTERN. */
2207 re_char *p1;
2208
2209 /* Points to the end of the buffer, where we should append. */
2210 register unsigned char *b;
2211
2212 /* Keeps track of unclosed groups. */
2213 compile_stack_type compile_stack;
2214
2215 /* Points to the current (ending) position in the pattern. */
2216 #ifdef AIX
2217 /* `const' makes AIX compiler fail. */
2218 unsigned char *p = pattern;
2219 #else
2220 re_char *p = pattern;
2221 #endif
2222 re_char *pend = pattern + size;
2223
2224 /* How to translate the characters in the pattern. */
2225 RE_TRANSLATE_TYPE translate = bufp->translate;
2226
2227 /* Address of the count-byte of the most recently inserted `exactn'
2228 command. This makes it possible to tell if a new exact-match
2229 character can be added to that command or if the character requires
2230 a new `exactn' command. */
2231 unsigned char *pending_exact = 0;
2232
2233 /* Address of start of the most recently finished expression.
2234 This tells, e.g., postfix * where to find the start of its
2235 operand. Reset at the beginning of groups and alternatives. */
2236 unsigned char *laststart = 0;
2237
2238 /* Address of beginning of regexp, or inside of last group. */
2239 unsigned char *begalt;
2240
2241 /* Place in the uncompiled pattern (i.e., the {) to
2242 which to go back if the interval is invalid. */
2243 re_char *beg_interval;
2244
2245 /* Address of the place where a forward jump should go to the end of
2246 the containing expression. Each alternative of an `or' -- except the
2247 last -- ends with a forward jump of this sort. */
2248 unsigned char *fixup_alt_jump = 0;
2249
2250 /* Counts open-groups as they are encountered. Remembered for the
2251 matching close-group on the compile stack, so the same register
2252 number is put in the stop_memory as the start_memory. */
2253 regnum_t regnum = 0;
2254
2255 /* Work area for range table of charset. */
2256 struct range_table_work_area range_table_work;
2257
2258 /* If the object matched can contain multibyte characters. */
2259 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2260
2261 #ifdef DEBUG
2262 debug++;
2263 DEBUG_PRINT1 ("\nCompiling pattern: ");
2264 if (debug > 0)
2265 {
2266 unsigned debug_count;
2267
2268 for (debug_count = 0; debug_count < size; debug_count++)
2269 putchar (pattern[debug_count]);
2270 putchar ('\n');
2271 }
2272 #endif /* DEBUG */
2273
2274 /* Initialize the compile stack. */
2275 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2276 if (compile_stack.stack == NULL)
2277 return REG_ESPACE;
2278
2279 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2280 compile_stack.avail = 0;
2281
2282 range_table_work.table = 0;
2283 range_table_work.allocated = 0;
2284
2285 /* Initialize the pattern buffer. */
2286 bufp->syntax = syntax;
2287 bufp->fastmap_accurate = 0;
2288 bufp->not_bol = bufp->not_eol = 0;
2289
2290 /* Set `used' to zero, so that if we return an error, the pattern
2291 printer (for debugging) will think there's no pattern. We reset it
2292 at the end. */
2293 bufp->used = 0;
2294
2295 /* Always count groups, whether or not bufp->no_sub is set. */
2296 bufp->re_nsub = 0;
2297
2298 #if !defined emacs && !defined SYNTAX_TABLE
2299 /* Initialize the syntax table. */
2300 init_syntax_once ();
2301 #endif
2302
2303 if (bufp->allocated == 0)
2304 {
2305 if (bufp->buffer)
2306 { /* If zero allocated, but buffer is non-null, try to realloc
2307 enough space. This loses if buffer's address is bogus, but
2308 that is the user's responsibility. */
2309 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2310 }
2311 else
2312 { /* Caller did not allocate a buffer. Do it for them. */
2313 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2314 }
2315 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2316
2317 bufp->allocated = INIT_BUF_SIZE;
2318 }
2319
2320 begalt = b = bufp->buffer;
2321
2322 /* Loop through the uncompiled pattern until we're at the end. */
2323 while (p != pend)
2324 {
2325 PATFETCH_RAW (c);
2326
2327 switch (c)
2328 {
2329 case '^':
2330 {
2331 if ( /* If at start of pattern, it's an operator. */
2332 p == pattern + 1
2333 /* If context independent, it's an operator. */
2334 || syntax & RE_CONTEXT_INDEP_ANCHORS
2335 /* Otherwise, depends on what's come before. */
2336 || at_begline_loc_p (pattern, p, syntax))
2337 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2338 else
2339 goto normal_char;
2340 }
2341 break;
2342
2343
2344 case '$':
2345 {
2346 if ( /* If at end of pattern, it's an operator. */
2347 p == pend
2348 /* If context independent, it's an operator. */
2349 || syntax & RE_CONTEXT_INDEP_ANCHORS
2350 /* Otherwise, depends on what's next. */
2351 || at_endline_loc_p (p, pend, syntax))
2352 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2353 else
2354 goto normal_char;
2355 }
2356 break;
2357
2358
2359 case '+':
2360 case '?':
2361 if ((syntax & RE_BK_PLUS_QM)
2362 || (syntax & RE_LIMITED_OPS))
2363 goto normal_char;
2364 handle_plus:
2365 case '*':
2366 /* If there is no previous pattern... */
2367 if (!laststart)
2368 {
2369 if (syntax & RE_CONTEXT_INVALID_OPS)
2370 FREE_STACK_RETURN (REG_BADRPT);
2371 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2372 goto normal_char;
2373 }
2374
2375 {
2376 /* 1 means zero (many) matches is allowed. */
2377 boolean zero_times_ok = 0, many_times_ok = 0;
2378 boolean greedy = 1;
2379
2380 /* If there is a sequence of repetition chars, collapse it
2381 down to just one (the right one). We can't combine
2382 interval operators with these because of, e.g., `a{2}*',
2383 which should only match an even number of `a's. */
2384
2385 for (;;)
2386 {
2387 if ((syntax & RE_FRUGAL)
2388 && c == '?' && (zero_times_ok || many_times_ok))
2389 greedy = 0;
2390 else
2391 {
2392 zero_times_ok |= c != '+';
2393 many_times_ok |= c != '?';
2394 }
2395
2396 if (p == pend)
2397 break;
2398 else if (*p == '*'
2399 || (!(syntax & RE_BK_PLUS_QM)
2400 && (*p == '+' || *p == '?')))
2401 ;
2402 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2403 {
2404 if (p+1 == pend)
2405 FREE_STACK_RETURN (REG_EESCAPE);
2406 if (p[1] == '+' || p[1] == '?')
2407 PATFETCH_RAW (c); /* Gobble up the backslash. */
2408 else
2409 break;
2410 }
2411 else
2412 break;
2413 /* If we get here, we found another repeat character. */
2414 PATFETCH_RAW (c);
2415 }
2416
2417 /* Star, etc. applied to an empty pattern is equivalent
2418 to an empty pattern. */
2419 if (!laststart || laststart == b)
2420 break;
2421
2422 /* Now we know whether or not zero matches is allowed
2423 and also whether or not two or more matches is allowed. */
2424 if (greedy)
2425 {
2426 if (many_times_ok)
2427 {
2428 boolean simple = skip_one_char (laststart) == b;
2429 unsigned int startoffset = 0;
2430 re_opcode_t ofj =
2431 /* Check if the loop can match the empty string. */
2432 (simple || !analyse_first (laststart, b, NULL, 0)) ?
2433 on_failure_jump : on_failure_jump_loop;
2434 assert (skip_one_char (laststart) <= b);
2435
2436 if (!zero_times_ok && simple)
2437 { /* Since simple * loops can be made faster by using
2438 on_failure_keep_string_jump, we turn simple P+
2439 into PP* if P is simple. */
2440 unsigned char *p1, *p2;
2441 startoffset = b - laststart;
2442 GET_BUFFER_SPACE (startoffset);
2443 p1 = b; p2 = laststart;
2444 while (p2 < p1)
2445 *b++ = *p2++;
2446 zero_times_ok = 1;
2447 }
2448
2449 GET_BUFFER_SPACE (6);
2450 if (!zero_times_ok)
2451 /* A + loop. */
2452 STORE_JUMP (ofj, b, b + 6);
2453 else
2454 /* Simple * loops can use on_failure_keep_string_jump
2455 depending on what follows. But since we don't know
2456 that yet, we leave the decision up to
2457 on_failure_jump_smart. */
2458 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2459 laststart + startoffset, b + 6);
2460 b += 3;
2461 STORE_JUMP (jump, b, laststart + startoffset);
2462 b += 3;
2463 }
2464 else
2465 {
2466 /* A simple ? pattern. */
2467 assert (zero_times_ok);
2468 GET_BUFFER_SPACE (3);
2469 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2470 b += 3;
2471 }
2472 }
2473 else /* not greedy */
2474 { /* I wish the greedy and non-greedy cases could be merged. */
2475
2476 GET_BUFFER_SPACE (7); /* We might use less. */
2477 if (many_times_ok)
2478 {
2479 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2480
2481 /* The non-greedy multiple match looks like a repeat..until:
2482 we only need a conditional jump at the end of the loop */
2483 if (emptyp) BUF_PUSH (no_op);
2484 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2485 : on_failure_jump, b, laststart);
2486 b += 3;
2487 if (zero_times_ok)
2488 {
2489 /* The repeat...until naturally matches one or more.
2490 To also match zero times, we need to first jump to
2491 the end of the loop (its conditional jump). */
2492 INSERT_JUMP (jump, laststart, b);
2493 b += 3;
2494 }
2495 }
2496 else
2497 {
2498 /* non-greedy a?? */
2499 INSERT_JUMP (jump, laststart, b + 3);
2500 b += 3;
2501 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2502 b += 3;
2503 }
2504 }
2505 }
2506 pending_exact = 0;
2507 break;
2508
2509
2510 case '.':
2511 laststart = b;
2512 BUF_PUSH (anychar);
2513 break;
2514
2515
2516 case '[':
2517 {
2518 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2519
2520 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2521
2522 /* Ensure that we have enough space to push a charset: the
2523 opcode, the length count, and the bitset; 34 bytes in all. */
2524 GET_BUFFER_SPACE (34);
2525
2526 laststart = b;
2527
2528 /* We test `*p == '^' twice, instead of using an if
2529 statement, so we only need one BUF_PUSH. */
2530 BUF_PUSH (*p == '^' ? charset_not : charset);
2531 if (*p == '^')
2532 p++;
2533
2534 /* Remember the first position in the bracket expression. */
2535 p1 = p;
2536
2537 /* Push the number of bytes in the bitmap. */
2538 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2539
2540 /* Clear the whole map. */
2541 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2542
2543 /* charset_not matches newline according to a syntax bit. */
2544 if ((re_opcode_t) b[-2] == charset_not
2545 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2546 SET_LIST_BIT ('\n');
2547
2548 /* Read in characters and ranges, setting map bits. */
2549 for (;;)
2550 {
2551 boolean escaped_char = false;
2552 const unsigned char *p2 = p;
2553
2554 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2555
2556 PATFETCH_RAW (c);
2557
2558 /* \ might escape characters inside [...] and [^...]. */
2559 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2560 {
2561 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2562
2563 PATFETCH_RAW (c);
2564 escaped_char = true;
2565 }
2566 else
2567 {
2568 /* Could be the end of the bracket expression. If it's
2569 not (i.e., when the bracket expression is `[]' so
2570 far), the ']' character bit gets set way below. */
2571 if (c == ']' && p2 != p1)
2572 break;
2573 }
2574
2575 /* What should we do for the character which is
2576 greater than 0x7F, but not BASE_LEADING_CODE_P?
2577 XXX */
2578
2579 /* See if we're at the beginning of a possible character
2580 class. */
2581
2582 if (!escaped_char &&
2583 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2584 {
2585 /* Leave room for the null. */
2586 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2587 const unsigned char *class_beg;
2588
2589 PATFETCH_RAW (c);
2590 c1 = 0;
2591 class_beg = p;
2592
2593 /* If pattern is `[[:'. */
2594 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2595
2596 for (;;)
2597 {
2598 PATFETCH_RAW (c);
2599 if ((c == ':' && *p == ']') || p == pend)
2600 break;
2601 if (c1 < CHAR_CLASS_MAX_LENGTH)
2602 str[c1++] = c;
2603 else
2604 /* This is in any case an invalid class name. */
2605 str[0] = '\0';
2606 }
2607 str[c1] = '\0';
2608
2609 /* If isn't a word bracketed by `[:' and `:]':
2610 undo the ending character, the letters, and
2611 leave the leading `:' and `[' (but set bits for
2612 them). */
2613 if (c == ':' && *p == ']')
2614 {
2615 int ch;
2616 re_wctype_t cc;
2617
2618 cc = re_wctype (str);
2619
2620 if (cc == 0)
2621 FREE_STACK_RETURN (REG_ECTYPE);
2622
2623 /* Throw away the ] at the end of the character
2624 class. */
2625 PATFETCH_RAW (c);
2626
2627 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2628
2629 /* Most character classes in a multibyte match
2630 just set a flag. Exceptions are is_blank,
2631 is_digit, is_cntrl, and is_xdigit, since
2632 they can only match ASCII characters. We
2633 don't need to handle them for multibyte.
2634 They are distinguished by a negative wctype.
2635 We need this only for Emacs. */
2636 #ifdef emacs
2637 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2638 re_wctype_to_bit (cc));
2639 #endif
2640
2641 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2642 {
2643 MAKE_CHAR_MULTIBYTE (ch);
2644 ch = TRANSLATE (ch);
2645 if (IS_REAL_ASCII (ch)
2646 & re_iswctype (btowc (ch), cc))
2647 SET_LIST_BIT (ch);
2648 }
2649
2650 /* Repeat the loop. */
2651 continue;
2652 }
2653 else
2654 {
2655 /* Go back to right after the "[:". */
2656 p = class_beg;
2657 SET_LIST_BIT ('[');
2658
2659 /* Because the `:' may starts the range, we
2660 can't simply set bit and repeat the loop.
2661 Instead, just set it to C and handle below. */
2662 c = ':';
2663 }
2664 }
2665
2666 if (p < pend && p[0] == '-' && p[1] != ']')
2667 {
2668
2669 /* Discard the `-'. */
2670 PATFETCH_RAW (c1);
2671
2672 /* Fetch the character which ends the range. */
2673 PATFETCH_RAW (c1);
2674 #ifdef emacs
2675 if (multibyte)
2676 {
2677 c = TRANSLATE (c);
2678 c1 = TRANSLATE (c1);
2679 if (! IS_REAL_ASCII (c1))
2680 {
2681 SET_RANGE_TABLE_WORK_AREA (range_table_work,
2682 c, c1);
2683 c1 = 127;
2684 }
2685 }
2686 else
2687 {
2688 if (! IS_REAL_ASCII (c1))
2689 {
2690 int c2 = MAX (c, 128);
2691
2692 HANDLE_UNIBYTE_RANGE (range_table_work, c2, c1);
2693 c1 = 127;
2694 }
2695 }
2696 #endif
2697 }
2698 else
2699 {
2700 /* Range from C to C. */
2701 if (! multibyte)
2702 MAKE_CHAR_MULTIBYTE (c);
2703 c = TRANSLATE (c);
2704 if (IS_REAL_ASCII (c))
2705 c1 = c;
2706 else
2707 {
2708 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c);
2709 c = -1; /* Suppress setting bitmap. */
2710 }
2711 }
2712
2713 /* Set the range into bitmap */
2714 if (c >= 0)
2715 {
2716 re_wchar_t this_char;
2717 int range_start = c, range_end = c1;
2718
2719 /* If the start is after the end, the range is empty. */
2720 if (range_start > range_end)
2721 {
2722 if (syntax & RE_NO_EMPTY_RANGES)
2723 FREE_STACK_RETURN (REG_ERANGE);
2724 /* Else, repeat the loop. */
2725 }
2726 else
2727 {
2728 for (this_char = range_start; this_char <= range_end;
2729 this_char++)
2730 SET_LIST_BIT (TRANSLATE (this_char));
2731 }
2732 }
2733 }
2734
2735 /* Discard any (non)matching list bytes that are all 0 at the
2736 end of the map. Decrease the map-length byte too. */
2737 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2738 b[-1]--;
2739 b += b[-1];
2740
2741 /* Build real range table from work area. */
2742 if (RANGE_TABLE_WORK_USED (range_table_work)
2743 || RANGE_TABLE_WORK_BITS (range_table_work))
2744 {
2745 int i;
2746 int used = RANGE_TABLE_WORK_USED (range_table_work);
2747
2748 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2749 bytes for flags, two for COUNT, and three bytes for
2750 each character. */
2751 GET_BUFFER_SPACE (4 + used * 3);
2752
2753 /* Indicate the existence of range table. */
2754 laststart[1] |= 0x80;
2755
2756 /* Store the character class flag bits into the range table.
2757 If not in emacs, these flag bits are always 0. */
2758 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2759 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2760
2761 STORE_NUMBER_AND_INCR (b, used / 2);
2762 for (i = 0; i < used; i++)
2763 STORE_CHARACTER_AND_INCR
2764 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2765 }
2766 }
2767 break;
2768
2769
2770 case '(':
2771 if (syntax & RE_NO_BK_PARENS)
2772 goto handle_open;
2773 else
2774 goto normal_char;
2775
2776
2777 case ')':
2778 if (syntax & RE_NO_BK_PARENS)
2779 goto handle_close;
2780 else
2781 goto normal_char;
2782
2783
2784 case '\n':
2785 if (syntax & RE_NEWLINE_ALT)
2786 goto handle_alt;
2787 else
2788 goto normal_char;
2789
2790
2791 case '|':
2792 if (syntax & RE_NO_BK_VBAR)
2793 goto handle_alt;
2794 else
2795 goto normal_char;
2796
2797
2798 case '{':
2799 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2800 goto handle_interval;
2801 else
2802 goto normal_char;
2803
2804
2805 case '\\':
2806 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2807
2808 /* Do not translate the character after the \, so that we can
2809 distinguish, e.g., \B from \b, even if we normally would
2810 translate, e.g., B to b. */
2811 PATFETCH_RAW (c);
2812
2813 switch (c)
2814 {
2815 case '(':
2816 if (syntax & RE_NO_BK_PARENS)
2817 goto normal_backslash;
2818
2819 handle_open:
2820 {
2821 int shy = 0;
2822 if (p+1 < pend)
2823 {
2824 /* Look for a special (?...) construct */
2825 if ((syntax & RE_SHY_GROUPS) && *p == '?')
2826 {
2827 PATFETCH_RAW (c); /* Gobble up the '?'. */
2828 PATFETCH (c);
2829 switch (c)
2830 {
2831 case ':': shy = 1; break;
2832 default:
2833 /* Only (?:...) is supported right now. */
2834 FREE_STACK_RETURN (REG_BADPAT);
2835 }
2836 }
2837 }
2838
2839 if (!shy)
2840 {
2841 bufp->re_nsub++;
2842 regnum++;
2843 }
2844
2845 if (COMPILE_STACK_FULL)
2846 {
2847 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2848 compile_stack_elt_t);
2849 if (compile_stack.stack == NULL) return REG_ESPACE;
2850
2851 compile_stack.size <<= 1;
2852 }
2853
2854 /* These are the values to restore when we hit end of this
2855 group. They are all relative offsets, so that if the
2856 whole pattern moves because of realloc, they will still
2857 be valid. */
2858 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2859 COMPILE_STACK_TOP.fixup_alt_jump
2860 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2861 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2862 COMPILE_STACK_TOP.regnum = shy ? -regnum : regnum;
2863
2864 /* Do not push a
2865 start_memory for groups beyond the last one we can
2866 represent in the compiled pattern. */
2867 if (regnum <= MAX_REGNUM && !shy)
2868 BUF_PUSH_2 (start_memory, regnum);
2869
2870 compile_stack.avail++;
2871
2872 fixup_alt_jump = 0;
2873 laststart = 0;
2874 begalt = b;
2875 /* If we've reached MAX_REGNUM groups, then this open
2876 won't actually generate any code, so we'll have to
2877 clear pending_exact explicitly. */
2878 pending_exact = 0;
2879 break;
2880 }
2881
2882 case ')':
2883 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2884
2885 if (COMPILE_STACK_EMPTY)
2886 {
2887 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2888 goto normal_backslash;
2889 else
2890 FREE_STACK_RETURN (REG_ERPAREN);
2891 }
2892
2893 handle_close:
2894 FIXUP_ALT_JUMP ();
2895
2896 /* See similar code for backslashed left paren above. */
2897 if (COMPILE_STACK_EMPTY)
2898 {
2899 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2900 goto normal_char;
2901 else
2902 FREE_STACK_RETURN (REG_ERPAREN);
2903 }
2904
2905 /* Since we just checked for an empty stack above, this
2906 ``can't happen''. */
2907 assert (compile_stack.avail != 0);
2908 {
2909 /* We don't just want to restore into `regnum', because
2910 later groups should continue to be numbered higher,
2911 as in `(ab)c(de)' -- the second group is #2. */
2912 regnum_t this_group_regnum;
2913
2914 compile_stack.avail--;
2915 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2916 fixup_alt_jump
2917 = COMPILE_STACK_TOP.fixup_alt_jump
2918 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2919 : 0;
2920 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2921 this_group_regnum = COMPILE_STACK_TOP.regnum;
2922 /* If we've reached MAX_REGNUM groups, then this open
2923 won't actually generate any code, so we'll have to
2924 clear pending_exact explicitly. */
2925 pending_exact = 0;
2926
2927 /* We're at the end of the group, so now we know how many
2928 groups were inside this one. */
2929 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
2930 BUF_PUSH_2 (stop_memory, this_group_regnum);
2931 }
2932 break;
2933
2934
2935 case '|': /* `\|'. */
2936 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2937 goto normal_backslash;
2938 handle_alt:
2939 if (syntax & RE_LIMITED_OPS)
2940 goto normal_char;
2941
2942 /* Insert before the previous alternative a jump which
2943 jumps to this alternative if the former fails. */
2944 GET_BUFFER_SPACE (3);
2945 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2946 pending_exact = 0;
2947 b += 3;
2948
2949 /* The alternative before this one has a jump after it
2950 which gets executed if it gets matched. Adjust that
2951 jump so it will jump to this alternative's analogous
2952 jump (put in below, which in turn will jump to the next
2953 (if any) alternative's such jump, etc.). The last such
2954 jump jumps to the correct final destination. A picture:
2955 _____ _____
2956 | | | |
2957 | v | v
2958 a | b | c
2959
2960 If we are at `b', then fixup_alt_jump right now points to a
2961 three-byte space after `a'. We'll put in the jump, set
2962 fixup_alt_jump to right after `b', and leave behind three
2963 bytes which we'll fill in when we get to after `c'. */
2964
2965 FIXUP_ALT_JUMP ();
2966
2967 /* Mark and leave space for a jump after this alternative,
2968 to be filled in later either by next alternative or
2969 when know we're at the end of a series of alternatives. */
2970 fixup_alt_jump = b;
2971 GET_BUFFER_SPACE (3);
2972 b += 3;
2973
2974 laststart = 0;
2975 begalt = b;
2976 break;
2977
2978
2979 case '{':
2980 /* If \{ is a literal. */
2981 if (!(syntax & RE_INTERVALS)
2982 /* If we're at `\{' and it's not the open-interval
2983 operator. */
2984 || (syntax & RE_NO_BK_BRACES))
2985 goto normal_backslash;
2986
2987 handle_interval:
2988 {
2989 /* If got here, then the syntax allows intervals. */
2990
2991 /* At least (most) this many matches must be made. */
2992 int lower_bound = 0, upper_bound = -1;
2993
2994 beg_interval = p;
2995
2996 if (p == pend)
2997 FREE_STACK_RETURN (REG_EBRACE);
2998
2999 GET_UNSIGNED_NUMBER (lower_bound);
3000
3001 if (c == ',')
3002 GET_UNSIGNED_NUMBER (upper_bound);
3003 else
3004 /* Interval such as `{1}' => match exactly once. */
3005 upper_bound = lower_bound;
3006
3007 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3008 || (upper_bound >= 0 && lower_bound > upper_bound))
3009 FREE_STACK_RETURN (REG_BADBR);
3010
3011 if (!(syntax & RE_NO_BK_BRACES))
3012 {
3013 if (c != '\\')
3014 FREE_STACK_RETURN (REG_BADBR);
3015
3016 PATFETCH (c);
3017 }
3018
3019 if (c != '}')
3020 FREE_STACK_RETURN (REG_BADBR);
3021
3022 /* We just parsed a valid interval. */
3023
3024 /* If it's invalid to have no preceding re. */
3025 if (!laststart)
3026 {
3027 if (syntax & RE_CONTEXT_INVALID_OPS)
3028 FREE_STACK_RETURN (REG_BADRPT);
3029 else if (syntax & RE_CONTEXT_INDEP_OPS)
3030 laststart = b;
3031 else
3032 goto unfetch_interval;
3033 }
3034
3035 if (upper_bound == 0)
3036 /* If the upper bound is zero, just drop the sub pattern
3037 altogether. */
3038 b = laststart;
3039 else if (lower_bound == 1 && upper_bound == 1)
3040 /* Just match it once: nothing to do here. */
3041 ;
3042
3043 /* Otherwise, we have a nontrivial interval. When
3044 we're all done, the pattern will look like:
3045 set_number_at <jump count> <upper bound>
3046 set_number_at <succeed_n count> <lower bound>
3047 succeed_n <after jump addr> <succeed_n count>
3048 <body of loop>
3049 jump_n <succeed_n addr> <jump count>
3050 (The upper bound and `jump_n' are omitted if
3051 `upper_bound' is 1, though.) */
3052 else
3053 { /* If the upper bound is > 1, we need to insert
3054 more at the end of the loop. */
3055 unsigned int nbytes = (upper_bound < 0 ? 3
3056 : upper_bound > 1 ? 5 : 0);
3057 unsigned int startoffset = 0;
3058
3059 GET_BUFFER_SPACE (20); /* We might use less. */
3060
3061 if (lower_bound == 0)
3062 {
3063 /* A succeed_n that starts with 0 is really a
3064 a simple on_failure_jump_loop. */
3065 INSERT_JUMP (on_failure_jump_loop, laststart,
3066 b + 3 + nbytes);
3067 b += 3;
3068 }
3069 else
3070 {
3071 /* Initialize lower bound of the `succeed_n', even
3072 though it will be set during matching by its
3073 attendant `set_number_at' (inserted next),
3074 because `re_compile_fastmap' needs to know.
3075 Jump to the `jump_n' we might insert below. */
3076 INSERT_JUMP2 (succeed_n, laststart,
3077 b + 5 + nbytes,
3078 lower_bound);
3079 b += 5;
3080
3081 /* Code to initialize the lower bound. Insert
3082 before the `succeed_n'. The `5' is the last two
3083 bytes of this `set_number_at', plus 3 bytes of
3084 the following `succeed_n'. */
3085 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3086 b += 5;
3087 startoffset += 5;
3088 }
3089
3090 if (upper_bound < 0)
3091 {
3092 /* A negative upper bound stands for infinity,
3093 in which case it degenerates to a plain jump. */
3094 STORE_JUMP (jump, b, laststart + startoffset);
3095 b += 3;
3096 }
3097 else if (upper_bound > 1)
3098 { /* More than one repetition is allowed, so
3099 append a backward jump to the `succeed_n'
3100 that starts this interval.
3101
3102 When we've reached this during matching,
3103 we'll have matched the interval once, so
3104 jump back only `upper_bound - 1' times. */
3105 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3106 upper_bound - 1);
3107 b += 5;
3108
3109 /* The location we want to set is the second
3110 parameter of the `jump_n'; that is `b-2' as
3111 an absolute address. `laststart' will be
3112 the `set_number_at' we're about to insert;
3113 `laststart+3' the number to set, the source
3114 for the relative address. But we are
3115 inserting into the middle of the pattern --
3116 so everything is getting moved up by 5.
3117 Conclusion: (b - 2) - (laststart + 3) + 5,
3118 i.e., b - laststart.
3119
3120 We insert this at the beginning of the loop
3121 so that if we fail during matching, we'll
3122 reinitialize the bounds. */
3123 insert_op2 (set_number_at, laststart, b - laststart,
3124 upper_bound - 1, b);
3125 b += 5;
3126 }
3127 }
3128 pending_exact = 0;
3129 beg_interval = NULL;
3130 }
3131 break;
3132
3133 unfetch_interval:
3134 /* If an invalid interval, match the characters as literals. */
3135 assert (beg_interval);
3136 p = beg_interval;
3137 beg_interval = NULL;
3138
3139 /* normal_char and normal_backslash need `c'. */
3140 c = '{';
3141
3142 if (!(syntax & RE_NO_BK_BRACES))
3143 {
3144 assert (p > pattern && p[-1] == '\\');
3145 goto normal_backslash;
3146 }
3147 else
3148 goto normal_char;
3149
3150 #ifdef emacs
3151 /* There is no way to specify the before_dot and after_dot
3152 operators. rms says this is ok. --karl */
3153 case '=':
3154 BUF_PUSH (at_dot);
3155 break;
3156
3157 case 's':
3158 laststart = b;
3159 PATFETCH (c);
3160 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3161 break;
3162
3163 case 'S':
3164 laststart = b;
3165 PATFETCH (c);
3166 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3167 break;
3168
3169 case 'c':
3170 laststart = b;
3171 PATFETCH_RAW (c);
3172 BUF_PUSH_2 (categoryspec, c);
3173 break;
3174
3175 case 'C':
3176 laststart = b;
3177 PATFETCH_RAW (c);
3178 BUF_PUSH_2 (notcategoryspec, c);
3179 break;
3180 #endif /* emacs */
3181
3182
3183 case 'w':
3184 if (syntax & RE_NO_GNU_OPS)
3185 goto normal_char;
3186 laststart = b;
3187 BUF_PUSH_2 (syntaxspec, Sword);
3188 break;
3189
3190
3191 case 'W':
3192 if (syntax & RE_NO_GNU_OPS)
3193 goto normal_char;
3194 laststart = b;
3195 BUF_PUSH_2 (notsyntaxspec, Sword);
3196 break;
3197
3198
3199 case '<':
3200 if (syntax & RE_NO_GNU_OPS)
3201 goto normal_char;
3202 BUF_PUSH (wordbeg);
3203 break;
3204
3205 case '>':
3206 if (syntax & RE_NO_GNU_OPS)
3207 goto normal_char;
3208 BUF_PUSH (wordend);
3209 break;
3210
3211 case 'b':
3212 if (syntax & RE_NO_GNU_OPS)
3213 goto normal_char;
3214 BUF_PUSH (wordbound);
3215 break;
3216
3217 case 'B':
3218 if (syntax & RE_NO_GNU_OPS)
3219 goto normal_char;
3220 BUF_PUSH (notwordbound);
3221 break;
3222
3223 case '`':
3224 if (syntax & RE_NO_GNU_OPS)
3225 goto normal_char;
3226 BUF_PUSH (begbuf);
3227 break;
3228
3229 case '\'':
3230 if (syntax & RE_NO_GNU_OPS)
3231 goto normal_char;
3232 BUF_PUSH (endbuf);
3233 break;
3234
3235 case '1': case '2': case '3': case '4': case '5':
3236 case '6': case '7': case '8': case '9':
3237 {
3238 regnum_t reg;
3239
3240 if (syntax & RE_NO_BK_REFS)
3241 goto normal_backslash;
3242
3243 reg = c - '0';
3244
3245 /* Can't back reference to a subexpression before its end. */
3246 if (reg > regnum || group_in_compile_stack (compile_stack, reg))
3247 FREE_STACK_RETURN (REG_ESUBREG);
3248
3249 laststart = b;
3250 BUF_PUSH_2 (duplicate, reg);
3251 }
3252 break;
3253
3254
3255 case '+':
3256 case '?':
3257 if (syntax & RE_BK_PLUS_QM)
3258 goto handle_plus;
3259 else
3260 goto normal_backslash;
3261
3262 default:
3263 normal_backslash:
3264 /* You might think it would be useful for \ to mean
3265 not to translate; but if we don't translate it
3266 it will never match anything. */
3267 c = TRANSLATE (c);
3268 goto normal_char;
3269 }
3270 break;
3271
3272
3273 default:
3274 /* Expects the character in `c'. */
3275 normal_char:
3276 /* If no exactn currently being built. */
3277 if (!pending_exact
3278
3279 /* If last exactn not at current position. */
3280 || pending_exact + *pending_exact + 1 != b
3281
3282 /* We have only one byte following the exactn for the count. */
3283 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3284
3285 /* If followed by a repetition operator. */
3286 || (p != pend && (*p == '*' || *p == '^'))
3287 || ((syntax & RE_BK_PLUS_QM)
3288 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3289 : p != pend && (*p == '+' || *p == '?'))
3290 || ((syntax & RE_INTERVALS)
3291 && ((syntax & RE_NO_BK_BRACES)
3292 ? p != pend && *p == '{'
3293 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3294 {
3295 /* Start building a new exactn. */
3296
3297 laststart = b;
3298
3299 BUF_PUSH_2 (exactn, 0);
3300 pending_exact = b - 1;
3301 }
3302
3303 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3304 {
3305 int len;
3306
3307 if (! multibyte)
3308 MAKE_CHAR_MULTIBYTE (c);
3309 c = TRANSLATE (c);
3310 len = CHAR_STRING (c, b);
3311 b += len;
3312 (*pending_exact) += len;
3313 }
3314
3315 break;
3316 } /* switch (c) */
3317 } /* while p != pend */
3318
3319
3320 /* Through the pattern now. */
3321
3322 FIXUP_ALT_JUMP ();
3323
3324 if (!COMPILE_STACK_EMPTY)
3325 FREE_STACK_RETURN (REG_EPAREN);
3326
3327 /* If we don't want backtracking, force success
3328 the first time we reach the end of the compiled pattern. */
3329 if (syntax & RE_NO_POSIX_BACKTRACKING)
3330 BUF_PUSH (succeed);
3331
3332 free (compile_stack.stack);
3333
3334 /* We have succeeded; set the length of the buffer. */
3335 bufp->used = b - bufp->buffer;
3336
3337 #ifdef DEBUG
3338 if (debug > 0)
3339 {
3340 re_compile_fastmap (bufp);
3341 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3342 print_compiled_pattern (bufp);
3343 }
3344 debug--;
3345 #endif /* DEBUG */
3346
3347 #ifndef MATCH_MAY_ALLOCATE
3348 /* Initialize the failure stack to the largest possible stack. This
3349 isn't necessary unless we're trying to avoid calling alloca in
3350 the search and match routines. */
3351 {
3352 int num_regs = bufp->re_nsub + 1;
3353
3354 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3355 {
3356 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3357
3358 if (! fail_stack.stack)
3359 fail_stack.stack
3360 = (fail_stack_elt_t *) malloc (fail_stack.size
3361 * sizeof (fail_stack_elt_t));
3362 else
3363 fail_stack.stack
3364 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3365 (fail_stack.size
3366 * sizeof (fail_stack_elt_t)));
3367 }
3368
3369 regex_grow_registers (num_regs);
3370 }
3371 #endif /* not MATCH_MAY_ALLOCATE */
3372
3373 return REG_NOERROR;
3374 } /* regex_compile */
3375 \f
3376 /* Subroutines for `regex_compile'. */
3377
3378 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3379
3380 static void
3381 store_op1 (op, loc, arg)
3382 re_opcode_t op;
3383 unsigned char *loc;
3384 int arg;
3385 {
3386 *loc = (unsigned char) op;
3387 STORE_NUMBER (loc + 1, arg);
3388 }
3389
3390
3391 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3392
3393 static void
3394 store_op2 (op, loc, arg1, arg2)
3395 re_opcode_t op;
3396 unsigned char *loc;
3397 int arg1, arg2;
3398 {
3399 *loc = (unsigned char) op;
3400 STORE_NUMBER (loc + 1, arg1);
3401 STORE_NUMBER (loc + 3, arg2);
3402 }
3403
3404
3405 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3406 for OP followed by two-byte integer parameter ARG. */
3407
3408 static void
3409 insert_op1 (op, loc, arg, end)
3410 re_opcode_t op;
3411 unsigned char *loc;
3412 int arg;
3413 unsigned char *end;
3414 {
3415 register unsigned char *pfrom = end;
3416 register unsigned char *pto = end + 3;
3417
3418 while (pfrom != loc)
3419 *--pto = *--pfrom;
3420
3421 store_op1 (op, loc, arg);
3422 }
3423
3424
3425 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3426
3427 static void
3428 insert_op2 (op, loc, arg1, arg2, end)
3429 re_opcode_t op;
3430 unsigned char *loc;
3431 int arg1, arg2;
3432 unsigned char *end;
3433 {
3434 register unsigned char *pfrom = end;
3435 register unsigned char *pto = end + 5;
3436
3437 while (pfrom != loc)
3438 *--pto = *--pfrom;
3439
3440 store_op2 (op, loc, arg1, arg2);
3441 }
3442
3443
3444 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3445 after an alternative or a begin-subexpression. We assume there is at
3446 least one character before the ^. */
3447
3448 static boolean
3449 at_begline_loc_p (pattern, p, syntax)
3450 re_char *pattern, *p;
3451 reg_syntax_t syntax;
3452 {
3453 re_char *prev = p - 2;
3454 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3455
3456 return
3457 /* After a subexpression? */
3458 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3459 /* After an alternative? */
3460 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3461 /* After a shy subexpression? */
3462 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3463 && prev[-1] == '?' && prev[-2] == '('
3464 && (syntax & RE_NO_BK_PARENS
3465 || (prev - 3 >= pattern && prev[-3] == '\\')));
3466 }
3467
3468
3469 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3470 at least one character after the $, i.e., `P < PEND'. */
3471
3472 static boolean
3473 at_endline_loc_p (p, pend, syntax)
3474 re_char *p, *pend;
3475 reg_syntax_t syntax;
3476 {
3477 re_char *next = p;
3478 boolean next_backslash = *next == '\\';
3479 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3480
3481 return
3482 /* Before a subexpression? */
3483 (syntax & RE_NO_BK_PARENS ? *next == ')'
3484 : next_backslash && next_next && *next_next == ')')
3485 /* Before an alternative? */
3486 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3487 : next_backslash && next_next && *next_next == '|');
3488 }
3489
3490
3491 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3492 false if it's not. */
3493
3494 static boolean
3495 group_in_compile_stack (compile_stack, regnum)
3496 compile_stack_type compile_stack;
3497 regnum_t regnum;
3498 {
3499 int this_element;
3500
3501 for (this_element = compile_stack.avail - 1;
3502 this_element >= 0;
3503 this_element--)
3504 if (compile_stack.stack[this_element].regnum == regnum)
3505 return true;
3506
3507 return false;
3508 }
3509 \f
3510 /* analyse_first.
3511 If fastmap is non-NULL, go through the pattern and fill fastmap
3512 with all the possible leading chars. If fastmap is NULL, don't
3513 bother filling it up (obviously) and only return whether the
3514 pattern could potentially match the empty string.
3515
3516 MULTIBYTE is always 1 for Emacs, and 0 otherwise.
3517
3518 Return 1 if p..pend might match the empty string.
3519 Return 0 if p..pend matches at least one char.
3520 Return -1 if fastmap was not updated accurately. */
3521
3522 static int
3523 analyse_first (p, pend, fastmap, multibyte)
3524 re_char *p, *pend;
3525 char *fastmap;
3526 const int multibyte;
3527 {
3528 int j, k;
3529 boolean not;
3530
3531 /* If all elements for base leading-codes in fastmap is set, this
3532 flag is set true. */
3533 boolean match_any_multibyte_characters = false;
3534
3535 assert (p);
3536
3537 /* The loop below works as follows:
3538 - It has a working-list kept in the PATTERN_STACK and which basically
3539 starts by only containing a pointer to the first operation.
3540 - If the opcode we're looking at is a match against some set of
3541 chars, then we add those chars to the fastmap and go on to the
3542 next work element from the worklist (done via `break').
3543 - If the opcode is a control operator on the other hand, we either
3544 ignore it (if it's meaningless at this point, such as `start_memory')
3545 or execute it (if it's a jump). If the jump has several destinations
3546 (i.e. `on_failure_jump'), then we push the other destination onto the
3547 worklist.
3548 We guarantee termination by ignoring backward jumps (more or less),
3549 so that `p' is monotonically increasing. More to the point, we
3550 never set `p' (or push) anything `<= p1'. */
3551
3552 while (p < pend)
3553 {
3554 /* `p1' is used as a marker of how far back a `on_failure_jump'
3555 can go without being ignored. It is normally equal to `p'
3556 (which prevents any backward `on_failure_jump') except right
3557 after a plain `jump', to allow patterns such as:
3558 0: jump 10
3559 3..9: <body>
3560 10: on_failure_jump 3
3561 as used for the *? operator. */
3562 re_char *p1 = p;
3563
3564 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3565 {
3566 case succeed:
3567 return 1;
3568 continue;
3569
3570 case duplicate:
3571 /* If the first character has to match a backreference, that means
3572 that the group was empty (since it already matched). Since this
3573 is the only case that interests us here, we can assume that the
3574 backreference must match the empty string. */
3575 p++;
3576 continue;
3577
3578
3579 /* Following are the cases which match a character. These end
3580 with `break'. */
3581
3582 case exactn:
3583 if (fastmap)
3584 /* If multibyte is nonzero, the first byte of each
3585 character is an ASCII or a leading code. Otherwise,
3586 each byte is a character. Thus, this works in both
3587 cases. */
3588 fastmap[p[1]] = 1;
3589 break;
3590
3591
3592 case anychar:
3593 /* We could put all the chars except for \n (and maybe \0)
3594 but we don't bother since it is generally not worth it. */
3595 if (!fastmap) break;
3596 return -1;
3597
3598
3599 case charset_not:
3600 if (!fastmap) break;
3601 {
3602 /* Chars beyond end of bitmap are possible matches. */
3603 /* Emacs uses the bitmap only for ASCII characters. */
3604 int limit = multibyte ? 128 : (1 << BYTEWIDTH);
3605
3606 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3607 j < limit; j++)
3608 fastmap[j] = 1;
3609 }
3610
3611 /* Fallthrough */
3612 case charset:
3613 if (!fastmap) break;
3614 not = (re_opcode_t) *(p - 1) == charset_not;
3615 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3616 j >= 0; j--)
3617 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3618 fastmap[j] = 1;
3619
3620 if ((not && multibyte)
3621 /* Any leading code can possibly start a character
3622 which doesn't match the specified set of characters. */
3623 || (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3624 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3625 /* If we can match a character class, we can match
3626 any character set. */
3627 {
3628 set_fastmap_for_multibyte_characters:
3629 if (match_any_multibyte_characters == false)
3630 {
3631 for (j = 0x80; j < 0x100; j++) /* XXX */
3632 if (BASE_LEADING_CODE_P (j))
3633 fastmap[j] = 1;
3634 match_any_multibyte_characters = true;
3635 }
3636 }
3637
3638 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3639 && match_any_multibyte_characters == false)
3640 {
3641 /* Set fastmap[I] to 1 where I is a leading code of each
3642 multibyte characer in the range table. */
3643 int c, count;
3644 unsigned char lc1, lc2;
3645
3646 /* Make P points the range table. `+ 2' is to skip flag
3647 bits for a character class. */
3648 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3649
3650 /* Extract the number of ranges in range table into COUNT. */
3651 EXTRACT_NUMBER_AND_INCR (count, p);
3652 for (; count > 0; count--, p += 2 * 3) /* XXX */
3653 {
3654 /* Extract the start and end of each range. */
3655 EXTRACT_CHARACTER (c, p);
3656 lc1 = CHAR_LEADING_CODE (c);
3657 p += 3;
3658 EXTRACT_CHARACTER (c, p);
3659 lc2 = CHAR_LEADING_CODE (c);
3660 for (j = lc1; j <= lc2; j++)
3661 fastmap[j] = 1;
3662 }
3663 }
3664 break;
3665
3666 case syntaxspec:
3667 case notsyntaxspec:
3668 if (!fastmap) break;
3669 #ifndef emacs
3670 not = (re_opcode_t)p[-1] == notsyntaxspec;
3671 k = *p++;
3672 for (j = 0; j < (1 << BYTEWIDTH); j++)
3673 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3674 fastmap[j] = 1;
3675 break;
3676 #else /* emacs */
3677 /* This match depends on text properties. These end with
3678 aborting optimizations. */
3679 return -1;
3680
3681 case categoryspec:
3682 case notcategoryspec:
3683 if (!fastmap) break;
3684 not = (re_opcode_t)p[-1] == notcategoryspec;
3685 k = *p++;
3686 for (j = (multibyte ? 127 : (1 << BYTEWIDTH)); j >= 0; j--)
3687 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3688 fastmap[j] = 1;
3689
3690 if (multibyte)
3691 /* Any character set can possibly contain a character
3692 whose category is K (or not). */
3693 goto set_fastmap_for_multibyte_characters;
3694 break;
3695
3696 /* All cases after this match the empty string. These end with
3697 `continue'. */
3698
3699 case before_dot:
3700 case at_dot:
3701 case after_dot:
3702 #endif /* !emacs */
3703 case no_op:
3704 case begline:
3705 case endline:
3706 case begbuf:
3707 case endbuf:
3708 case wordbound:
3709 case notwordbound:
3710 case wordbeg:
3711 case wordend:
3712 continue;
3713
3714
3715 case jump:
3716 EXTRACT_NUMBER_AND_INCR (j, p);
3717 if (j < 0)
3718 /* Backward jumps can only go back to code that we've already
3719 visited. `re_compile' should make sure this is true. */
3720 break;
3721 p += j;
3722 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3723 {
3724 case on_failure_jump:
3725 case on_failure_keep_string_jump:
3726 case on_failure_jump_loop:
3727 case on_failure_jump_nastyloop:
3728 case on_failure_jump_smart:
3729 p++;
3730 break;
3731 default:
3732 continue;
3733 };
3734 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3735 to jump back to "just after here". */
3736 /* Fallthrough */
3737
3738 case on_failure_jump:
3739 case on_failure_keep_string_jump:
3740 case on_failure_jump_nastyloop:
3741 case on_failure_jump_loop:
3742 case on_failure_jump_smart:
3743 EXTRACT_NUMBER_AND_INCR (j, p);
3744 if (p + j <= p1)
3745 ; /* Backward jump to be ignored. */
3746 else
3747 { /* We have to look down both arms.
3748 We first go down the "straight" path so as to minimize
3749 stack usage when going through alternatives. */
3750 int r = analyse_first (p, pend, fastmap, multibyte);
3751 if (r) return r;
3752 p += j;
3753 }
3754 continue;
3755
3756
3757 case jump_n:
3758 /* This code simply does not properly handle forward jump_n. */
3759 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
3760 p += 4;
3761 /* jump_n can either jump or fall through. The (backward) jump
3762 case has already been handled, so we only need to look at the
3763 fallthrough case. */
3764 continue;
3765
3766 case succeed_n:
3767 /* If N == 0, it should be an on_failure_jump_loop instead. */
3768 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
3769 p += 4;
3770 /* We only care about one iteration of the loop, so we don't
3771 need to consider the case where this behaves like an
3772 on_failure_jump. */
3773 continue;
3774
3775
3776 case set_number_at:
3777 p += 4;
3778 continue;
3779
3780
3781 case start_memory:
3782 case stop_memory:
3783 p += 1;
3784 continue;
3785
3786
3787 default:
3788 abort (); /* We have listed all the cases. */
3789 } /* switch *p++ */
3790
3791 /* Getting here means we have found the possible starting
3792 characters for one path of the pattern -- and that the empty
3793 string does not match. We need not follow this path further. */
3794 return 0;
3795 } /* while p */
3796
3797 /* We reached the end without matching anything. */
3798 return 1;
3799
3800 } /* analyse_first */
3801 \f
3802 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3803 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3804 characters can start a string that matches the pattern. This fastmap
3805 is used by re_search to skip quickly over impossible starting points.
3806
3807 Character codes above (1 << BYTEWIDTH) are not represented in the
3808 fastmap, but the leading codes are represented. Thus, the fastmap
3809 indicates which character sets could start a match.
3810
3811 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3812 area as BUFP->fastmap.
3813
3814 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3815 the pattern buffer.
3816
3817 Returns 0 if we succeed, -2 if an internal error. */
3818
3819 int
3820 re_compile_fastmap (bufp)
3821 struct re_pattern_buffer *bufp;
3822 {
3823 char *fastmap = bufp->fastmap;
3824 int analysis;
3825
3826 assert (fastmap && bufp->buffer);
3827
3828 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3829 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3830
3831 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
3832 fastmap,
3833 #ifdef emacs
3834 /* The compiled pattern buffer is always
3835 setup for multibyte characters. */
3836 1
3837 #else
3838 0
3839 #endif
3840 );
3841 bufp->can_be_null = (analysis != 0);
3842 return 0;
3843 } /* re_compile_fastmap */
3844 \f
3845 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3846 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3847 this memory for recording register information. STARTS and ENDS
3848 must be allocated using the malloc library routine, and must each
3849 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3850
3851 If NUM_REGS == 0, then subsequent matches should allocate their own
3852 register data.
3853
3854 Unless this function is called, the first search or match using
3855 PATTERN_BUFFER will allocate its own register data, without
3856 freeing the old data. */
3857
3858 void
3859 re_set_registers (bufp, regs, num_regs, starts, ends)
3860 struct re_pattern_buffer *bufp;
3861 struct re_registers *regs;
3862 unsigned num_regs;
3863 regoff_t *starts, *ends;
3864 {
3865 if (num_regs)
3866 {
3867 bufp->regs_allocated = REGS_REALLOCATE;
3868 regs->num_regs = num_regs;
3869 regs->start = starts;
3870 regs->end = ends;
3871 }
3872 else
3873 {
3874 bufp->regs_allocated = REGS_UNALLOCATED;
3875 regs->num_regs = 0;
3876 regs->start = regs->end = (regoff_t *) 0;
3877 }
3878 }
3879 WEAK_ALIAS (__re_set_registers, re_set_registers)
3880 \f
3881 /* Searching routines. */
3882
3883 /* Like re_search_2, below, but only one string is specified, and
3884 doesn't let you say where to stop matching. */
3885
3886 int
3887 re_search (bufp, string, size, startpos, range, regs)
3888 struct re_pattern_buffer *bufp;
3889 const char *string;
3890 int size, startpos, range;
3891 struct re_registers *regs;
3892 {
3893 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3894 regs, size);
3895 }
3896 WEAK_ALIAS (__re_search, re_search)
3897
3898 /* End address of virtual concatenation of string. */
3899 #define STOP_ADDR_VSTRING(P) \
3900 (((P) >= size1 ? string2 + size2 : string1 + size1))
3901
3902 /* Address of POS in the concatenation of virtual string. */
3903 #define POS_ADDR_VSTRING(POS) \
3904 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3905
3906 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3907 virtual concatenation of STRING1 and STRING2, starting first at index
3908 STARTPOS, then at STARTPOS + 1, and so on.
3909
3910 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3911
3912 RANGE is how far to scan while trying to match. RANGE = 0 means try
3913 only at STARTPOS; in general, the last start tried is STARTPOS +
3914 RANGE.
3915
3916 In REGS, return the indices of the virtual concatenation of STRING1
3917 and STRING2 that matched the entire BUFP->buffer and its contained
3918 subexpressions.
3919
3920 Do not consider matching one past the index STOP in the virtual
3921 concatenation of STRING1 and STRING2.
3922
3923 We return either the position in the strings at which the match was
3924 found, -1 if no match, or -2 if error (such as failure
3925 stack overflow). */
3926
3927 int
3928 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
3929 struct re_pattern_buffer *bufp;
3930 const char *str1, *str2;
3931 int size1, size2;
3932 int startpos;
3933 int range;
3934 struct re_registers *regs;
3935 int stop;
3936 {
3937 int val;
3938 re_char *string1 = (re_char*) str1;
3939 re_char *string2 = (re_char*) str2;
3940 register char *fastmap = bufp->fastmap;
3941 register RE_TRANSLATE_TYPE translate = bufp->translate;
3942 int total_size = size1 + size2;
3943 int endpos = startpos + range;
3944 boolean anchored_start;
3945
3946 /* Nonzero if BUFP is setup for multibyte characters. */
3947 #ifdef emacs
3948 const boolean multibyte = 1;
3949 #else
3950 const boolean multibyte = 0;
3951 #endif
3952 /* Nonzero if STR1 and STR2 contains multibyte characters. */
3953 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
3954
3955 /* Check for out-of-range STARTPOS. */
3956 if (startpos < 0 || startpos > total_size)
3957 return -1;
3958
3959 /* Fix up RANGE if it might eventually take us outside
3960 the virtual concatenation of STRING1 and STRING2.
3961 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3962 if (endpos < 0)
3963 range = 0 - startpos;
3964 else if (endpos > total_size)
3965 range = total_size - startpos;
3966
3967 /* If the search isn't to be a backwards one, don't waste time in a
3968 search for a pattern anchored at beginning of buffer. */
3969 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3970 {
3971 if (startpos > 0)
3972 return -1;
3973 else
3974 range = 0;
3975 }
3976
3977 #ifdef emacs
3978 /* In a forward search for something that starts with \=.
3979 don't keep searching past point. */
3980 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3981 {
3982 range = PT_BYTE - BEGV_BYTE - startpos;
3983 if (range < 0)
3984 return -1;
3985 }
3986 #endif /* emacs */
3987
3988 /* Update the fastmap now if not correct already. */
3989 if (fastmap && !bufp->fastmap_accurate)
3990 re_compile_fastmap (bufp);
3991
3992 /* See whether the pattern is anchored. */
3993 anchored_start = (bufp->buffer[0] == begline);
3994
3995 #ifdef emacs
3996 gl_state.object = re_match_object;
3997 {
3998 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
3999
4000 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4001 }
4002 #endif
4003
4004 /* Loop through the string, looking for a place to start matching. */
4005 for (;;)
4006 {
4007 /* If the pattern is anchored,
4008 skip quickly past places we cannot match.
4009 We don't bother to treat startpos == 0 specially
4010 because that case doesn't repeat. */
4011 if (anchored_start && startpos > 0)
4012 {
4013 if (! ((startpos <= size1 ? string1[startpos - 1]
4014 : string2[startpos - size1 - 1])
4015 == '\n'))
4016 goto advance;
4017 }
4018
4019 /* If a fastmap is supplied, skip quickly over characters that
4020 cannot be the start of a match. If the pattern can match the
4021 null string, however, we don't need to skip characters; we want
4022 the first null string. */
4023 if (fastmap && startpos < total_size && !bufp->can_be_null)
4024 {
4025 register re_char *d;
4026 register re_wchar_t buf_ch;
4027
4028 d = POS_ADDR_VSTRING (startpos);
4029
4030 if (range > 0) /* Searching forwards. */
4031 {
4032 register int lim = 0;
4033 int irange = range;
4034
4035 if (startpos < size1 && startpos + range >= size1)
4036 lim = range - (size1 - startpos);
4037
4038 /* Written out as an if-else to avoid testing `translate'
4039 inside the loop. */
4040 if (RE_TRANSLATE_P (translate))
4041 {
4042 if (target_multibyte)
4043 while (range > lim)
4044 {
4045 int buf_charlen;
4046
4047 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
4048 buf_charlen);
4049
4050 buf_ch = RE_TRANSLATE (translate, buf_ch);
4051 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4052 break;
4053
4054 range -= buf_charlen;
4055 d += buf_charlen;
4056 }
4057 else if (multibyte)
4058 while (range > lim)
4059 {
4060 buf_ch = *d;
4061 MAKE_CHAR_MULTIBYTE (buf_ch);
4062 buf_ch = RE_TRANSLATE (translate, buf_ch);
4063 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4064 break;
4065
4066 d++;
4067 range--;
4068 }
4069 else
4070 while (range > lim
4071 && !fastmap[RE_TRANSLATE (translate, *d)])
4072 {
4073 d++;
4074 range--;
4075 }
4076 }
4077 else if (multibyte && ! target_multibyte)
4078 {
4079 buf_ch = *d;
4080 MAKE_CHAR_MULTIBYTE (buf_ch);
4081 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4082 break;
4083
4084 d++;
4085 range--;
4086 }
4087 else
4088 while (range > lim && !fastmap[*d])
4089 {
4090 d++;
4091 range--;
4092 }
4093
4094 startpos += irange - range;
4095 }
4096 else /* Searching backwards. */
4097 {
4098 int room = (startpos >= size1
4099 ? size2 + size1 - startpos
4100 : size1 - startpos);
4101 buf_ch = RE_STRING_CHAR (d, room);
4102 if (! target_multibyte)
4103 MAKE_CHAR_MULTIBYTE (buf_ch);
4104 buf_ch = TRANSLATE (buf_ch);
4105
4106 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4107 goto advance;
4108 }
4109 }
4110
4111 /* If can't match the null string, and that's all we have left, fail. */
4112 if (range >= 0 && startpos == total_size && fastmap
4113 && !bufp->can_be_null)
4114 return -1;
4115
4116 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4117 startpos, regs, stop);
4118 #ifndef REGEX_MALLOC
4119 # ifdef C_ALLOCA
4120 alloca (0);
4121 # endif
4122 #endif
4123
4124 if (val >= 0)
4125 return startpos;
4126
4127 if (val == -2)
4128 return -2;
4129
4130 advance:
4131 if (!range)
4132 break;
4133 else if (range > 0)
4134 {
4135 /* Update STARTPOS to the next character boundary. */
4136 if (target_multibyte)
4137 {
4138 re_char *p = POS_ADDR_VSTRING (startpos);
4139 re_char *pend = STOP_ADDR_VSTRING (startpos);
4140 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
4141
4142 range -= len;
4143 if (range < 0)
4144 break;
4145 startpos += len;
4146 }
4147 else
4148 {
4149 range--;
4150 startpos++;
4151 }
4152 }
4153 else
4154 {
4155 range++;
4156 startpos--;
4157
4158 /* Update STARTPOS to the previous character boundary. */
4159 if (target_multibyte)
4160 {
4161 re_char *p = POS_ADDR_VSTRING (startpos);
4162 int len = 0;
4163
4164 /* Find the head of multibyte form. */
4165 while (!CHAR_HEAD_P (*p))
4166 p--, len++;
4167
4168 /* Adjust it. */
4169 #if 0 /* XXX */
4170 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
4171 ;
4172 else
4173 #endif
4174 {
4175 range += len;
4176 if (range > 0)
4177 break;
4178
4179 startpos -= len;
4180 }
4181 }
4182 }
4183 }
4184 return -1;
4185 } /* re_search_2 */
4186 WEAK_ALIAS (__re_search_2, re_search_2)
4187 \f
4188 /* Declarations and macros for re_match_2. */
4189
4190 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4191 register int len,
4192 RE_TRANSLATE_TYPE translate,
4193 const int multibyte));
4194
4195 /* This converts PTR, a pointer into one of the search strings `string1'
4196 and `string2' into an offset from the beginning of that string. */
4197 #define POINTER_TO_OFFSET(ptr) \
4198 (FIRST_STRING_P (ptr) \
4199 ? ((regoff_t) ((ptr) - string1)) \
4200 : ((regoff_t) ((ptr) - string2 + size1)))
4201
4202 /* Call before fetching a character with *d. This switches over to
4203 string2 if necessary.
4204 Check re_match_2_internal for a discussion of why end_match_2 might
4205 not be within string2 (but be equal to end_match_1 instead). */
4206 #define PREFETCH() \
4207 while (d == dend) \
4208 { \
4209 /* End of string2 => fail. */ \
4210 if (dend == end_match_2) \
4211 goto fail; \
4212 /* End of string1 => advance to string2. */ \
4213 d = string2; \
4214 dend = end_match_2; \
4215 }
4216
4217 /* Call before fetching a char with *d if you already checked other limits.
4218 This is meant for use in lookahead operations like wordend, etc..
4219 where we might need to look at parts of the string that might be
4220 outside of the LIMITs (i.e past `stop'). */
4221 #define PREFETCH_NOLIMIT() \
4222 if (d == end1) \
4223 { \
4224 d = string2; \
4225 dend = end_match_2; \
4226 } \
4227
4228 /* Test if at very beginning or at very end of the virtual concatenation
4229 of `string1' and `string2'. If only one string, it's `string2'. */
4230 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4231 #define AT_STRINGS_END(d) ((d) == end2)
4232
4233
4234 /* Test if D points to a character which is word-constituent. We have
4235 two special cases to check for: if past the end of string1, look at
4236 the first character in string2; and if before the beginning of
4237 string2, look at the last character in string1. */
4238 #define WORDCHAR_P(d) \
4239 (SYNTAX ((d) == end1 ? *string2 \
4240 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4241 == Sword)
4242
4243 /* Disabled due to a compiler bug -- see comment at case wordbound */
4244
4245 /* The comment at case wordbound is following one, but we don't use
4246 AT_WORD_BOUNDARY anymore to support multibyte form.
4247
4248 The DEC Alpha C compiler 3.x generates incorrect code for the
4249 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4250 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4251 macro and introducing temporary variables works around the bug. */
4252
4253 #if 0
4254 /* Test if the character before D and the one at D differ with respect
4255 to being word-constituent. */
4256 #define AT_WORD_BOUNDARY(d) \
4257 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4258 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4259 #endif
4260
4261 /* Free everything we malloc. */
4262 #ifdef MATCH_MAY_ALLOCATE
4263 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4264 # define FREE_VARIABLES() \
4265 do { \
4266 REGEX_FREE_STACK (fail_stack.stack); \
4267 FREE_VAR (regstart); \
4268 FREE_VAR (regend); \
4269 FREE_VAR (best_regstart); \
4270 FREE_VAR (best_regend); \
4271 } while (0)
4272 #else
4273 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4274 #endif /* not MATCH_MAY_ALLOCATE */
4275
4276 \f
4277 /* Optimization routines. */
4278
4279 /* If the operation is a match against one or more chars,
4280 return a pointer to the next operation, else return NULL. */
4281 static re_char *
4282 skip_one_char (p)
4283 re_char *p;
4284 {
4285 switch (SWITCH_ENUM_CAST (*p++))
4286 {
4287 case anychar:
4288 break;
4289
4290 case exactn:
4291 p += *p + 1;
4292 break;
4293
4294 case charset_not:
4295 case charset:
4296 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4297 {
4298 int mcnt;
4299 p = CHARSET_RANGE_TABLE (p - 1);
4300 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4301 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4302 }
4303 else
4304 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4305 break;
4306
4307 case syntaxspec:
4308 case notsyntaxspec:
4309 #ifdef emacs
4310 case categoryspec:
4311 case notcategoryspec:
4312 #endif /* emacs */
4313 p++;
4314 break;
4315
4316 default:
4317 p = NULL;
4318 }
4319 return p;
4320 }
4321
4322
4323 /* Jump over non-matching operations. */
4324 static unsigned char *
4325 skip_noops (p, pend)
4326 unsigned char *p, *pend;
4327 {
4328 int mcnt;
4329 while (p < pend)
4330 {
4331 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4332 {
4333 case start_memory:
4334 case stop_memory:
4335 p += 2; break;
4336 case no_op:
4337 p += 1; break;
4338 case jump:
4339 p += 1;
4340 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4341 p += mcnt;
4342 break;
4343 default:
4344 return p;
4345 }
4346 }
4347 assert (p == pend);
4348 return p;
4349 }
4350
4351 /* Non-zero if "p1 matches something" implies "p2 fails". */
4352 static int
4353 mutually_exclusive_p (bufp, p1, p2)
4354 struct re_pattern_buffer *bufp;
4355 unsigned char *p1, *p2;
4356 {
4357 re_opcode_t op2;
4358 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4359 unsigned char *pend = bufp->buffer + bufp->used;
4360
4361 assert (p1 >= bufp->buffer && p1 < pend
4362 && p2 >= bufp->buffer && p2 <= pend);
4363
4364 /* Skip over open/close-group commands.
4365 If what follows this loop is a ...+ construct,
4366 look at what begins its body, since we will have to
4367 match at least one of that. */
4368 p2 = skip_noops (p2, pend);
4369 /* The same skip can be done for p1, except that this function
4370 is only used in the case where p1 is a simple match operator. */
4371 /* p1 = skip_noops (p1, pend); */
4372
4373 assert (p1 >= bufp->buffer && p1 < pend
4374 && p2 >= bufp->buffer && p2 <= pend);
4375
4376 op2 = p2 == pend ? succeed : *p2;
4377
4378 switch (SWITCH_ENUM_CAST (op2))
4379 {
4380 case succeed:
4381 case endbuf:
4382 /* If we're at the end of the pattern, we can change. */
4383 if (skip_one_char (p1))
4384 {
4385 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4386 return 1;
4387 }
4388 break;
4389
4390 case endline:
4391 case exactn:
4392 {
4393 register re_wchar_t c
4394 = (re_opcode_t) *p2 == endline ? '\n'
4395 : RE_STRING_CHAR (p2 + 2, pend - p2 - 2);
4396
4397 if ((re_opcode_t) *p1 == exactn)
4398 {
4399 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4400 {
4401 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4402 return 1;
4403 }
4404 }
4405
4406 else if ((re_opcode_t) *p1 == charset
4407 || (re_opcode_t) *p1 == charset_not)
4408 {
4409 int not = (re_opcode_t) *p1 == charset_not;
4410
4411 /* Test if C is listed in charset (or charset_not)
4412 at `p1'. */
4413 if (SINGLE_BYTE_CHAR_P (c))
4414 {
4415 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4416 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4417 not = !not;
4418 }
4419 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4420 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4421
4422 /* `not' is equal to 1 if c would match, which means
4423 that we can't change to pop_failure_jump. */
4424 if (!not)
4425 {
4426 DEBUG_PRINT1 (" No match => fast loop.\n");
4427 return 1;
4428 }
4429 }
4430 else if ((re_opcode_t) *p1 == anychar
4431 && c == '\n')
4432 {
4433 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4434 return 1;
4435 }
4436 }
4437 break;
4438
4439 case charset:
4440 {
4441 if ((re_opcode_t) *p1 == exactn)
4442 /* Reuse the code above. */
4443 return mutually_exclusive_p (bufp, p2, p1);
4444
4445 /* It is hard to list up all the character in charset
4446 P2 if it includes multibyte character. Give up in
4447 such case. */
4448 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4449 {
4450 /* Now, we are sure that P2 has no range table.
4451 So, for the size of bitmap in P2, `p2[1]' is
4452 enough. But P1 may have range table, so the
4453 size of bitmap table of P1 is extracted by
4454 using macro `CHARSET_BITMAP_SIZE'.
4455
4456 Since we know that all the character listed in
4457 P2 is ASCII, it is enough to test only bitmap
4458 table of P1. */
4459
4460 if ((re_opcode_t) *p1 == charset)
4461 {
4462 int idx;
4463 /* We win if the charset inside the loop
4464 has no overlap with the one after the loop. */
4465 for (idx = 0;
4466 (idx < (int) p2[1]
4467 && idx < CHARSET_BITMAP_SIZE (p1));
4468 idx++)
4469 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4470 break;
4471
4472 if (idx == p2[1]
4473 || idx == CHARSET_BITMAP_SIZE (p1))
4474 {
4475 DEBUG_PRINT1 (" No match => fast loop.\n");
4476 return 1;
4477 }
4478 }
4479 else if ((re_opcode_t) *p1 == charset_not)
4480 {
4481 int idx;
4482 /* We win if the charset_not inside the loop lists
4483 every character listed in the charset after. */
4484 for (idx = 0; idx < (int) p2[1]; idx++)
4485 if (! (p2[2 + idx] == 0
4486 || (idx < CHARSET_BITMAP_SIZE (p1)
4487 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4488 break;
4489
4490 if (idx == p2[1])
4491 {
4492 DEBUG_PRINT1 (" No match => fast loop.\n");
4493 return 1;
4494 }
4495 }
4496 }
4497 }
4498 break;
4499
4500 case charset_not:
4501 switch (SWITCH_ENUM_CAST (*p1))
4502 {
4503 case exactn:
4504 case charset:
4505 /* Reuse the code above. */
4506 return mutually_exclusive_p (bufp, p2, p1);
4507 case charset_not:
4508 /* When we have two charset_not, it's very unlikely that
4509 they don't overlap. The union of the two sets of excluded
4510 chars should cover all possible chars, which, as a matter of
4511 fact, is virtually impossible in multibyte buffers. */
4512 ;
4513 }
4514 break;
4515
4516 case wordend:
4517 case notsyntaxspec:
4518 return ((re_opcode_t) *p1 == syntaxspec
4519 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4520
4521 case wordbeg:
4522 case syntaxspec:
4523 return ((re_opcode_t) *p1 == notsyntaxspec
4524 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4525
4526 case wordbound:
4527 return (((re_opcode_t) *p1 == notsyntaxspec
4528 || (re_opcode_t) *p1 == syntaxspec)
4529 && p1[1] == Sword);
4530
4531 #ifdef emacs
4532 case categoryspec:
4533 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4534 case notcategoryspec:
4535 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4536 #endif /* emacs */
4537
4538 default:
4539 ;
4540 }
4541
4542 /* Safe default. */
4543 return 0;
4544 }
4545
4546 \f
4547 /* Matching routines. */
4548
4549 #ifndef emacs /* Emacs never uses this. */
4550 /* re_match is like re_match_2 except it takes only a single string. */
4551
4552 int
4553 re_match (bufp, string, size, pos, regs)
4554 struct re_pattern_buffer *bufp;
4555 const char *string;
4556 int size, pos;
4557 struct re_registers *regs;
4558 {
4559 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4560 pos, regs, size);
4561 # if defined C_ALLOCA && !defined REGEX_MALLOC
4562 alloca (0);
4563 # endif
4564 return result;
4565 }
4566 WEAK_ALIAS (__re_match, re_match)
4567 #endif /* not emacs */
4568
4569 #ifdef emacs
4570 /* In Emacs, this is the string or buffer in which we
4571 are matching. It is used for looking up syntax properties. */
4572 Lisp_Object re_match_object;
4573 #endif
4574
4575 /* re_match_2 matches the compiled pattern in BUFP against the
4576 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4577 and SIZE2, respectively). We start matching at POS, and stop
4578 matching at STOP.
4579
4580 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4581 store offsets for the substring each group matched in REGS. See the
4582 documentation for exactly how many groups we fill.
4583
4584 We return -1 if no match, -2 if an internal error (such as the
4585 failure stack overflowing). Otherwise, we return the length of the
4586 matched substring. */
4587
4588 int
4589 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4590 struct re_pattern_buffer *bufp;
4591 const char *string1, *string2;
4592 int size1, size2;
4593 int pos;
4594 struct re_registers *regs;
4595 int stop;
4596 {
4597 int result;
4598
4599 #ifdef emacs
4600 int charpos;
4601 gl_state.object = re_match_object;
4602 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4603 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4604 #endif
4605
4606 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4607 (re_char*) string2, size2,
4608 pos, regs, stop);
4609 #if defined C_ALLOCA && !defined REGEX_MALLOC
4610 alloca (0);
4611 #endif
4612 return result;
4613 }
4614 WEAK_ALIAS (__re_match_2, re_match_2)
4615
4616 #ifdef emacs
4617 #define TARGET_CHAR_AND_LENGTH(d, len, actual_len) \
4618 (target_multibyte \
4619 ? STRING_CHAR_AND_LENGTH (d, len, actual_len) \
4620 : (actual_len = 1, unibyte_char_to_multibyte (*d)))
4621 #else
4622 #define TARGET_CHAR_AND_LENGTH(d, len, actual_len) \
4623 (actual_len = 1, *d)
4624 #endif
4625
4626
4627 /* This is a separate function so that we can force an alloca cleanup
4628 afterwards. */
4629 static int
4630 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4631 struct re_pattern_buffer *bufp;
4632 re_char *string1, *string2;
4633 int size1, size2;
4634 int pos;
4635 struct re_registers *regs;
4636 int stop;
4637 {
4638 /* General temporaries. */
4639 int mcnt;
4640 size_t reg;
4641 boolean not;
4642
4643 /* Just past the end of the corresponding string. */
4644 re_char *end1, *end2;
4645
4646 /* Pointers into string1 and string2, just past the last characters in
4647 each to consider matching. */
4648 re_char *end_match_1, *end_match_2;
4649
4650 /* Where we are in the data, and the end of the current string. */
4651 re_char *d, *dend;
4652
4653 /* Used sometimes to remember where we were before starting matching
4654 an operator so that we can go back in case of failure. This "atomic"
4655 behavior of matching opcodes is indispensable to the correctness
4656 of the on_failure_keep_string_jump optimization. */
4657 re_char *dfail;
4658
4659 /* Where we are in the pattern, and the end of the pattern. */
4660 re_char *p = bufp->buffer;
4661 re_char *pend = p + bufp->used;
4662
4663 /* We use this to map every character in the string. */
4664 RE_TRANSLATE_TYPE translate = bufp->translate;
4665
4666 /* Nonzero if BUFP is setup for multibyte characters. */
4667 #ifdef emacs
4668 const boolean multibyte = 1;
4669 #else
4670 const boolean multibyte = 0;
4671 #endif
4672 /* Nonzero if STR1 and STR2 contains multibyte characters. */
4673 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4674
4675 /* Failure point stack. Each place that can handle a failure further
4676 down the line pushes a failure point on this stack. It consists of
4677 regstart, and regend for all registers corresponding to
4678 the subexpressions we're currently inside, plus the number of such
4679 registers, and, finally, two char *'s. The first char * is where
4680 to resume scanning the pattern; the second one is where to resume
4681 scanning the strings. */
4682 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4683 fail_stack_type fail_stack;
4684 #endif
4685 #ifdef DEBUG
4686 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4687 #endif
4688
4689 #if defined REL_ALLOC && defined REGEX_MALLOC
4690 /* This holds the pointer to the failure stack, when
4691 it is allocated relocatably. */
4692 fail_stack_elt_t *failure_stack_ptr;
4693 #endif
4694
4695 /* We fill all the registers internally, independent of what we
4696 return, for use in backreferences. The number here includes
4697 an element for register zero. */
4698 size_t num_regs = bufp->re_nsub + 1;
4699
4700 /* Information on the contents of registers. These are pointers into
4701 the input strings; they record just what was matched (on this
4702 attempt) by a subexpression part of the pattern, that is, the
4703 regnum-th regstart pointer points to where in the pattern we began
4704 matching and the regnum-th regend points to right after where we
4705 stopped matching the regnum-th subexpression. (The zeroth register
4706 keeps track of what the whole pattern matches.) */
4707 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4708 re_char **regstart, **regend;
4709 #endif
4710
4711 /* The following record the register info as found in the above
4712 variables when we find a match better than any we've seen before.
4713 This happens as we backtrack through the failure points, which in
4714 turn happens only if we have not yet matched the entire string. */
4715 unsigned best_regs_set = false;
4716 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4717 re_char **best_regstart, **best_regend;
4718 #endif
4719
4720 /* Logically, this is `best_regend[0]'. But we don't want to have to
4721 allocate space for that if we're not allocating space for anything
4722 else (see below). Also, we never need info about register 0 for
4723 any of the other register vectors, and it seems rather a kludge to
4724 treat `best_regend' differently than the rest. So we keep track of
4725 the end of the best match so far in a separate variable. We
4726 initialize this to NULL so that when we backtrack the first time
4727 and need to test it, it's not garbage. */
4728 re_char *match_end = NULL;
4729
4730 #ifdef DEBUG
4731 /* Counts the total number of registers pushed. */
4732 unsigned num_regs_pushed = 0;
4733 #endif
4734
4735 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4736
4737 INIT_FAIL_STACK ();
4738
4739 #ifdef MATCH_MAY_ALLOCATE
4740 /* Do not bother to initialize all the register variables if there are
4741 no groups in the pattern, as it takes a fair amount of time. If
4742 there are groups, we include space for register 0 (the whole
4743 pattern), even though we never use it, since it simplifies the
4744 array indexing. We should fix this. */
4745 if (bufp->re_nsub)
4746 {
4747 regstart = REGEX_TALLOC (num_regs, re_char *);
4748 regend = REGEX_TALLOC (num_regs, re_char *);
4749 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4750 best_regend = REGEX_TALLOC (num_regs, re_char *);
4751
4752 if (!(regstart && regend && best_regstart && best_regend))
4753 {
4754 FREE_VARIABLES ();
4755 return -2;
4756 }
4757 }
4758 else
4759 {
4760 /* We must initialize all our variables to NULL, so that
4761 `FREE_VARIABLES' doesn't try to free them. */
4762 regstart = regend = best_regstart = best_regend = NULL;
4763 }
4764 #endif /* MATCH_MAY_ALLOCATE */
4765
4766 /* The starting position is bogus. */
4767 if (pos < 0 || pos > size1 + size2)
4768 {
4769 FREE_VARIABLES ();
4770 return -1;
4771 }
4772
4773 /* Initialize subexpression text positions to -1 to mark ones that no
4774 start_memory/stop_memory has been seen for. Also initialize the
4775 register information struct. */
4776 for (reg = 1; reg < num_regs; reg++)
4777 regstart[reg] = regend[reg] = NULL;
4778
4779 /* We move `string1' into `string2' if the latter's empty -- but not if
4780 `string1' is null. */
4781 if (size2 == 0 && string1 != NULL)
4782 {
4783 string2 = string1;
4784 size2 = size1;
4785 string1 = 0;
4786 size1 = 0;
4787 }
4788 end1 = string1 + size1;
4789 end2 = string2 + size2;
4790
4791 /* `p' scans through the pattern as `d' scans through the data.
4792 `dend' is the end of the input string that `d' points within. `d'
4793 is advanced into the following input string whenever necessary, but
4794 this happens before fetching; therefore, at the beginning of the
4795 loop, `d' can be pointing at the end of a string, but it cannot
4796 equal `string2'. */
4797 if (pos >= size1)
4798 {
4799 /* Only match within string2. */
4800 d = string2 + pos - size1;
4801 dend = end_match_2 = string2 + stop - size1;
4802 end_match_1 = end1; /* Just to give it a value. */
4803 }
4804 else
4805 {
4806 if (stop < size1)
4807 {
4808 /* Only match within string1. */
4809 end_match_1 = string1 + stop;
4810 /* BEWARE!
4811 When we reach end_match_1, PREFETCH normally switches to string2.
4812 But in the present case, this means that just doing a PREFETCH
4813 makes us jump from `stop' to `gap' within the string.
4814 What we really want here is for the search to stop as
4815 soon as we hit end_match_1. That's why we set end_match_2
4816 to end_match_1 (since PREFETCH fails as soon as we hit
4817 end_match_2). */
4818 end_match_2 = end_match_1;
4819 }
4820 else
4821 { /* It's important to use this code when stop == size so that
4822 moving `d' from end1 to string2 will not prevent the d == dend
4823 check from catching the end of string. */
4824 end_match_1 = end1;
4825 end_match_2 = string2 + stop - size1;
4826 }
4827 d = string1 + pos;
4828 dend = end_match_1;
4829 }
4830
4831 DEBUG_PRINT1 ("The compiled pattern is: ");
4832 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4833 DEBUG_PRINT1 ("The string to match is: `");
4834 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4835 DEBUG_PRINT1 ("'\n");
4836
4837 /* This loops over pattern commands. It exits by returning from the
4838 function if the match is complete, or it drops through if the match
4839 fails at this starting point in the input data. */
4840 for (;;)
4841 {
4842 DEBUG_PRINT2 ("\n%p: ", p);
4843
4844 if (p == pend)
4845 { /* End of pattern means we might have succeeded. */
4846 DEBUG_PRINT1 ("end of pattern ... ");
4847
4848 /* If we haven't matched the entire string, and we want the
4849 longest match, try backtracking. */
4850 if (d != end_match_2)
4851 {
4852 /* 1 if this match ends in the same string (string1 or string2)
4853 as the best previous match. */
4854 boolean same_str_p = (FIRST_STRING_P (match_end)
4855 == FIRST_STRING_P (d));
4856 /* 1 if this match is the best seen so far. */
4857 boolean best_match_p;
4858
4859 /* AIX compiler got confused when this was combined
4860 with the previous declaration. */
4861 if (same_str_p)
4862 best_match_p = d > match_end;
4863 else
4864 best_match_p = !FIRST_STRING_P (d);
4865
4866 DEBUG_PRINT1 ("backtracking.\n");
4867
4868 if (!FAIL_STACK_EMPTY ())
4869 { /* More failure points to try. */
4870
4871 /* If exceeds best match so far, save it. */
4872 if (!best_regs_set || best_match_p)
4873 {
4874 best_regs_set = true;
4875 match_end = d;
4876
4877 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4878
4879 for (reg = 1; reg < num_regs; reg++)
4880 {
4881 best_regstart[reg] = regstart[reg];
4882 best_regend[reg] = regend[reg];
4883 }
4884 }
4885 goto fail;
4886 }
4887
4888 /* If no failure points, don't restore garbage. And if
4889 last match is real best match, don't restore second
4890 best one. */
4891 else if (best_regs_set && !best_match_p)
4892 {
4893 restore_best_regs:
4894 /* Restore best match. It may happen that `dend ==
4895 end_match_1' while the restored d is in string2.
4896 For example, the pattern `x.*y.*z' against the
4897 strings `x-' and `y-z-', if the two strings are
4898 not consecutive in memory. */
4899 DEBUG_PRINT1 ("Restoring best registers.\n");
4900
4901 d = match_end;
4902 dend = ((d >= string1 && d <= end1)
4903 ? end_match_1 : end_match_2);
4904
4905 for (reg = 1; reg < num_regs; reg++)
4906 {
4907 regstart[reg] = best_regstart[reg];
4908 regend[reg] = best_regend[reg];
4909 }
4910 }
4911 } /* d != end_match_2 */
4912
4913 succeed_label:
4914 DEBUG_PRINT1 ("Accepting match.\n");
4915
4916 /* If caller wants register contents data back, do it. */
4917 if (regs && !bufp->no_sub)
4918 {
4919 /* Have the register data arrays been allocated? */
4920 if (bufp->regs_allocated == REGS_UNALLOCATED)
4921 { /* No. So allocate them with malloc. We need one
4922 extra element beyond `num_regs' for the `-1' marker
4923 GNU code uses. */
4924 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4925 regs->start = TALLOC (regs->num_regs, regoff_t);
4926 regs->end = TALLOC (regs->num_regs, regoff_t);
4927 if (regs->start == NULL || regs->end == NULL)
4928 {
4929 FREE_VARIABLES ();
4930 return -2;
4931 }
4932 bufp->regs_allocated = REGS_REALLOCATE;
4933 }
4934 else if (bufp->regs_allocated == REGS_REALLOCATE)
4935 { /* Yes. If we need more elements than were already
4936 allocated, reallocate them. If we need fewer, just
4937 leave it alone. */
4938 if (regs->num_regs < num_regs + 1)
4939 {
4940 regs->num_regs = num_regs + 1;
4941 RETALLOC (regs->start, regs->num_regs, regoff_t);
4942 RETALLOC (regs->end, regs->num_regs, regoff_t);
4943 if (regs->start == NULL || regs->end == NULL)
4944 {
4945 FREE_VARIABLES ();
4946 return -2;
4947 }
4948 }
4949 }
4950 else
4951 {
4952 /* These braces fend off a "empty body in an else-statement"
4953 warning under GCC when assert expands to nothing. */
4954 assert (bufp->regs_allocated == REGS_FIXED);
4955 }
4956
4957 /* Convert the pointer data in `regstart' and `regend' to
4958 indices. Register zero has to be set differently,
4959 since we haven't kept track of any info for it. */
4960 if (regs->num_regs > 0)
4961 {
4962 regs->start[0] = pos;
4963 regs->end[0] = POINTER_TO_OFFSET (d);
4964 }
4965
4966 /* Go through the first `min (num_regs, regs->num_regs)'
4967 registers, since that is all we initialized. */
4968 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
4969 {
4970 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
4971 regs->start[reg] = regs->end[reg] = -1;
4972 else
4973 {
4974 regs->start[reg]
4975 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
4976 regs->end[reg]
4977 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
4978 }
4979 }
4980
4981 /* If the regs structure we return has more elements than
4982 were in the pattern, set the extra elements to -1. If
4983 we (re)allocated the registers, this is the case,
4984 because we always allocate enough to have at least one
4985 -1 at the end. */
4986 for (reg = num_regs; reg < regs->num_regs; reg++)
4987 regs->start[reg] = regs->end[reg] = -1;
4988 } /* regs && !bufp->no_sub */
4989
4990 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4991 nfailure_points_pushed, nfailure_points_popped,
4992 nfailure_points_pushed - nfailure_points_popped);
4993 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4994
4995 mcnt = POINTER_TO_OFFSET (d) - pos;
4996
4997 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4998
4999 FREE_VARIABLES ();
5000 return mcnt;
5001 }
5002
5003 /* Otherwise match next pattern command. */
5004 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5005 {
5006 /* Ignore these. Used to ignore the n of succeed_n's which
5007 currently have n == 0. */
5008 case no_op:
5009 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5010 break;
5011
5012 case succeed:
5013 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5014 goto succeed_label;
5015
5016 /* Match the next n pattern characters exactly. The following
5017 byte in the pattern defines n, and the n bytes after that
5018 are the characters to match. */
5019 case exactn:
5020 mcnt = *p++;
5021 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5022
5023 /* Remember the start point to rollback upon failure. */
5024 dfail = d;
5025
5026 /* This is written out as an if-else so we don't waste time
5027 testing `translate' inside the loop. */
5028 if (RE_TRANSLATE_P (translate))
5029 {
5030 if (multibyte)
5031 do
5032 {
5033 int pat_charlen, buf_charlen;
5034 unsigned int pat_ch, buf_ch;
5035
5036 PREFETCH ();
5037 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
5038 buf_ch = TARGET_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
5039
5040 if (RE_TRANSLATE (translate, buf_ch)
5041 != pat_ch)
5042 {
5043 d = dfail;
5044 goto fail;
5045 }
5046
5047 p += pat_charlen;
5048 d += buf_charlen;
5049 mcnt -= pat_charlen;
5050 }
5051 while (mcnt > 0);
5052 else
5053 do
5054 {
5055 PREFETCH ();
5056 if (RE_TRANSLATE (translate, *d) != *p++)
5057 {
5058 d = dfail;
5059 goto fail;
5060 }
5061 d++;
5062 }
5063 while (--mcnt);
5064 }
5065 else
5066 {
5067 if (multibyte == target_multibyte)
5068 do
5069 {
5070 PREFETCH ();
5071 if (*d++ != *p++)
5072 {
5073 d = dfail;
5074 goto fail;
5075 }
5076 }
5077 while (--mcnt);
5078 else /* i.e. multibyte && ! target_multibyte */
5079 do
5080 {
5081 int pat_charlen, buf_charlen;
5082 unsigned int pat_ch, buf_ch;
5083
5084 PREFETCH ();
5085 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
5086 buf_ch = TARGET_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
5087
5088 if (pat_ch != buf_ch)
5089 {
5090 d = dfail;
5091 goto fail;
5092 }
5093 p += pat_charlen;
5094 d += buf_charlen;
5095 mcnt -= pat_charlen;
5096 }
5097 while (mcnt > 0);
5098 }
5099 break;
5100
5101
5102 /* Match any character except possibly a newline or a null. */
5103 case anychar:
5104 {
5105 int buf_charlen;
5106 re_wchar_t buf_ch;
5107
5108 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5109
5110 PREFETCH ();
5111 buf_ch = TARGET_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
5112 buf_ch = TRANSLATE (buf_ch);
5113
5114 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5115 && buf_ch == '\n')
5116 || ((bufp->syntax & RE_DOT_NOT_NULL)
5117 && buf_ch == '\000'))
5118 goto fail;
5119
5120 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5121 d += buf_charlen;
5122 }
5123 break;
5124
5125
5126 case charset:
5127 case charset_not:
5128 {
5129 register unsigned int c;
5130 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5131 int len;
5132
5133 /* Start of actual range_table, or end of bitmap if there is no
5134 range table. */
5135 re_char *range_table;
5136
5137 /* Nonzero if there is a range table. */
5138 int range_table_exists;
5139
5140 /* Number of ranges of range table. This is not included
5141 in the initial byte-length of the command. */
5142 int count = 0;
5143
5144 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5145
5146 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5147
5148 if (range_table_exists)
5149 {
5150 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5151 EXTRACT_NUMBER_AND_INCR (count, range_table);
5152 }
5153
5154 PREFETCH ();
5155 c = TARGET_CHAR_AND_LENGTH (d, dend - d, len);
5156 c = TRANSLATE (c); /* The character to match. */
5157
5158 if (! multibyte || IS_REAL_ASCII (c))
5159 { /* Lookup bitmap. */
5160 /* Cast to `unsigned' instead of `unsigned char' in
5161 case the bit list is a full 32 bytes long. */
5162 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5163 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5164 not = !not;
5165 }
5166 #ifdef emacs
5167 else if (range_table_exists)
5168 {
5169 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5170
5171 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5172 | (class_bits & BIT_MULTIBYTE)
5173 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5174 | (class_bits & BIT_SPACE && ISSPACE (c))
5175 | (class_bits & BIT_UPPER && ISUPPER (c))
5176 | (class_bits & BIT_WORD && ISWORD (c)))
5177 not = !not;
5178 else
5179 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5180 }
5181 #endif /* emacs */
5182
5183 if (range_table_exists)
5184 p = CHARSET_RANGE_TABLE_END (range_table, count);
5185 else
5186 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5187
5188 if (!not) goto fail;
5189
5190 d += len;
5191 break;
5192 }
5193
5194
5195 /* The beginning of a group is represented by start_memory.
5196 The argument is the register number. The text
5197 matched within the group is recorded (in the internal
5198 registers data structure) under the register number. */
5199 case start_memory:
5200 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5201
5202 /* In case we need to undo this operation (via backtracking). */
5203 PUSH_FAILURE_REG ((unsigned int)*p);
5204
5205 regstart[*p] = d;
5206 regend[*p] = NULL; /* probably unnecessary. -sm */
5207 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5208
5209 /* Move past the register number and inner group count. */
5210 p += 1;
5211 break;
5212
5213
5214 /* The stop_memory opcode represents the end of a group. Its
5215 argument is the same as start_memory's: the register number. */
5216 case stop_memory:
5217 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5218
5219 assert (!REG_UNSET (regstart[*p]));
5220 /* Strictly speaking, there should be code such as:
5221
5222 assert (REG_UNSET (regend[*p]));
5223 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5224
5225 But the only info to be pushed is regend[*p] and it is known to
5226 be UNSET, so there really isn't anything to push.
5227 Not pushing anything, on the other hand deprives us from the
5228 guarantee that regend[*p] is UNSET since undoing this operation
5229 will not reset its value properly. This is not important since
5230 the value will only be read on the next start_memory or at
5231 the very end and both events can only happen if this stop_memory
5232 is *not* undone. */
5233
5234 regend[*p] = d;
5235 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5236
5237 /* Move past the register number and the inner group count. */
5238 p += 1;
5239 break;
5240
5241
5242 /* \<digit> has been turned into a `duplicate' command which is
5243 followed by the numeric value of <digit> as the register number. */
5244 case duplicate:
5245 {
5246 register re_char *d2, *dend2;
5247 int regno = *p++; /* Get which register to match against. */
5248 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5249
5250 /* Can't back reference a group which we've never matched. */
5251 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5252 goto fail;
5253
5254 /* Where in input to try to start matching. */
5255 d2 = regstart[regno];
5256
5257 /* Remember the start point to rollback upon failure. */
5258 dfail = d;
5259
5260 /* Where to stop matching; if both the place to start and
5261 the place to stop matching are in the same string, then
5262 set to the place to stop, otherwise, for now have to use
5263 the end of the first string. */
5264
5265 dend2 = ((FIRST_STRING_P (regstart[regno])
5266 == FIRST_STRING_P (regend[regno]))
5267 ? regend[regno] : end_match_1);
5268 for (;;)
5269 {
5270 /* If necessary, advance to next segment in register
5271 contents. */
5272 while (d2 == dend2)
5273 {
5274 if (dend2 == end_match_2) break;
5275 if (dend2 == regend[regno]) break;
5276
5277 /* End of string1 => advance to string2. */
5278 d2 = string2;
5279 dend2 = regend[regno];
5280 }
5281 /* At end of register contents => success */
5282 if (d2 == dend2) break;
5283
5284 /* If necessary, advance to next segment in data. */
5285 PREFETCH ();
5286
5287 /* How many characters left in this segment to match. */
5288 mcnt = dend - d;
5289
5290 /* Want how many consecutive characters we can match in
5291 one shot, so, if necessary, adjust the count. */
5292 if (mcnt > dend2 - d2)
5293 mcnt = dend2 - d2;
5294
5295 /* Compare that many; failure if mismatch, else move
5296 past them. */
5297 if (RE_TRANSLATE_P (translate)
5298 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5299 : memcmp (d, d2, mcnt))
5300 {
5301 d = dfail;
5302 goto fail;
5303 }
5304 d += mcnt, d2 += mcnt;
5305 }
5306 }
5307 break;
5308
5309
5310 /* begline matches the empty string at the beginning of the string
5311 (unless `not_bol' is set in `bufp'), and after newlines. */
5312 case begline:
5313 DEBUG_PRINT1 ("EXECUTING begline.\n");
5314
5315 if (AT_STRINGS_BEG (d))
5316 {
5317 if (!bufp->not_bol) break;
5318 }
5319 else
5320 {
5321 unsigned c;
5322 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5323 if (c == '\n')
5324 break;
5325 }
5326 /* In all other cases, we fail. */
5327 goto fail;
5328
5329
5330 /* endline is the dual of begline. */
5331 case endline:
5332 DEBUG_PRINT1 ("EXECUTING endline.\n");
5333
5334 if (AT_STRINGS_END (d))
5335 {
5336 if (!bufp->not_eol) break;
5337 }
5338 else
5339 {
5340 PREFETCH_NOLIMIT ();
5341 if (*d == '\n')
5342 break;
5343 }
5344 goto fail;
5345
5346
5347 /* Match at the very beginning of the data. */
5348 case begbuf:
5349 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5350 if (AT_STRINGS_BEG (d))
5351 break;
5352 goto fail;
5353
5354
5355 /* Match at the very end of the data. */
5356 case endbuf:
5357 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5358 if (AT_STRINGS_END (d))
5359 break;
5360 goto fail;
5361
5362
5363 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5364 pushes NULL as the value for the string on the stack. Then
5365 `POP_FAILURE_POINT' will keep the current value for the
5366 string, instead of restoring it. To see why, consider
5367 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5368 then the . fails against the \n. But the next thing we want
5369 to do is match the \n against the \n; if we restored the
5370 string value, we would be back at the foo.
5371
5372 Because this is used only in specific cases, we don't need to
5373 check all the things that `on_failure_jump' does, to make
5374 sure the right things get saved on the stack. Hence we don't
5375 share its code. The only reason to push anything on the
5376 stack at all is that otherwise we would have to change
5377 `anychar's code to do something besides goto fail in this
5378 case; that seems worse than this. */
5379 case on_failure_keep_string_jump:
5380 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5381 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5382 mcnt, p + mcnt);
5383
5384 PUSH_FAILURE_POINT (p - 3, NULL);
5385 break;
5386
5387 /* A nasty loop is introduced by the non-greedy *? and +?.
5388 With such loops, the stack only ever contains one failure point
5389 at a time, so that a plain on_failure_jump_loop kind of
5390 cycle detection cannot work. Worse yet, such a detection
5391 can not only fail to detect a cycle, but it can also wrongly
5392 detect a cycle (between different instantiations of the same
5393 loop.
5394 So the method used for those nasty loops is a little different:
5395 We use a special cycle-detection-stack-frame which is pushed
5396 when the on_failure_jump_nastyloop failure-point is *popped*.
5397 This special frame thus marks the beginning of one iteration
5398 through the loop and we can hence easily check right here
5399 whether something matched between the beginning and the end of
5400 the loop. */
5401 case on_failure_jump_nastyloop:
5402 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5403 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5404 mcnt, p + mcnt);
5405
5406 assert ((re_opcode_t)p[-4] == no_op);
5407 CHECK_INFINITE_LOOP (p - 4, d);
5408 PUSH_FAILURE_POINT (p - 3, d);
5409 break;
5410
5411
5412 /* Simple loop detecting on_failure_jump: just check on the
5413 failure stack if the same spot was already hit earlier. */
5414 case on_failure_jump_loop:
5415 on_failure:
5416 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5417 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5418 mcnt, p + mcnt);
5419
5420 CHECK_INFINITE_LOOP (p - 3, d);
5421 PUSH_FAILURE_POINT (p - 3, d);
5422 break;
5423
5424
5425 /* Uses of on_failure_jump:
5426
5427 Each alternative starts with an on_failure_jump that points
5428 to the beginning of the next alternative. Each alternative
5429 except the last ends with a jump that in effect jumps past
5430 the rest of the alternatives. (They really jump to the
5431 ending jump of the following alternative, because tensioning
5432 these jumps is a hassle.)
5433
5434 Repeats start with an on_failure_jump that points past both
5435 the repetition text and either the following jump or
5436 pop_failure_jump back to this on_failure_jump. */
5437 case on_failure_jump:
5438 IMMEDIATE_QUIT_CHECK;
5439 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5440 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5441 mcnt, p + mcnt);
5442
5443 PUSH_FAILURE_POINT (p -3, d);
5444 break;
5445
5446 /* This operation is used for greedy *.
5447 Compare the beginning of the repeat with what in the
5448 pattern follows its end. If we can establish that there
5449 is nothing that they would both match, i.e., that we
5450 would have to backtrack because of (as in, e.g., `a*a')
5451 then we can use a non-backtracking loop based on
5452 on_failure_keep_string_jump instead of on_failure_jump. */
5453 case on_failure_jump_smart:
5454 IMMEDIATE_QUIT_CHECK;
5455 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5456 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5457 mcnt, p + mcnt);
5458 {
5459 re_char *p1 = p; /* Next operation. */
5460 /* Here, we discard `const', making re_match non-reentrant. */
5461 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5462 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5463
5464 p -= 3; /* Reset so that we will re-execute the
5465 instruction once it's been changed. */
5466
5467 EXTRACT_NUMBER (mcnt, p2 - 2);
5468
5469 /* Ensure this is a indeed the trivial kind of loop
5470 we are expecting. */
5471 assert (skip_one_char (p1) == p2 - 3);
5472 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5473 DEBUG_STATEMENT (debug += 2);
5474 if (mutually_exclusive_p (bufp, p1, p2))
5475 {
5476 /* Use a fast `on_failure_keep_string_jump' loop. */
5477 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5478 *p3 = (unsigned char) on_failure_keep_string_jump;
5479 STORE_NUMBER (p2 - 2, mcnt + 3);
5480 }
5481 else
5482 {
5483 /* Default to a safe `on_failure_jump' loop. */
5484 DEBUG_PRINT1 (" smart default => slow loop.\n");
5485 *p3 = (unsigned char) on_failure_jump;
5486 }
5487 DEBUG_STATEMENT (debug -= 2);
5488 }
5489 break;
5490
5491 /* Unconditionally jump (without popping any failure points). */
5492 case jump:
5493 unconditional_jump:
5494 IMMEDIATE_QUIT_CHECK;
5495 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5496 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5497 p += mcnt; /* Do the jump. */
5498 DEBUG_PRINT2 ("(to %p).\n", p);
5499 break;
5500
5501
5502 /* Have to succeed matching what follows at least n times.
5503 After that, handle like `on_failure_jump'. */
5504 case succeed_n:
5505 /* Signedness doesn't matter since we only compare MCNT to 0. */
5506 EXTRACT_NUMBER (mcnt, p + 2);
5507 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5508
5509 /* Originally, mcnt is how many times we HAVE to succeed. */
5510 if (mcnt != 0)
5511 {
5512 /* Here, we discard `const', making re_match non-reentrant. */
5513 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5514 mcnt--;
5515 p += 4;
5516 PUSH_NUMBER (p2, mcnt);
5517 }
5518 else
5519 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5520 goto on_failure;
5521 break;
5522
5523 case jump_n:
5524 /* Signedness doesn't matter since we only compare MCNT to 0. */
5525 EXTRACT_NUMBER (mcnt, p + 2);
5526 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5527
5528 /* Originally, this is how many times we CAN jump. */
5529 if (mcnt != 0)
5530 {
5531 /* Here, we discard `const', making re_match non-reentrant. */
5532 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5533 mcnt--;
5534 PUSH_NUMBER (p2, mcnt);
5535 goto unconditional_jump;
5536 }
5537 /* If don't have to jump any more, skip over the rest of command. */
5538 else
5539 p += 4;
5540 break;
5541
5542 case set_number_at:
5543 {
5544 unsigned char *p2; /* Location of the counter. */
5545 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5546
5547 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5548 /* Here, we discard `const', making re_match non-reentrant. */
5549 p2 = (unsigned char*) p + mcnt;
5550 /* Signedness doesn't matter since we only copy MCNT's bits . */
5551 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5552 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
5553 PUSH_NUMBER (p2, mcnt);
5554 break;
5555 }
5556
5557 case wordbound:
5558 case notwordbound:
5559 not = (re_opcode_t) *(p - 1) == notwordbound;
5560 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5561
5562 /* We SUCCEED (or FAIL) in one of the following cases: */
5563
5564 /* Case 1: D is at the beginning or the end of string. */
5565 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5566 not = !not;
5567 else
5568 {
5569 /* C1 is the character before D, S1 is the syntax of C1, C2
5570 is the character at D, and S2 is the syntax of C2. */
5571 re_wchar_t c1, c2;
5572 int s1, s2;
5573 int dummy;
5574 #ifdef emacs
5575 int offset = PTR_TO_OFFSET (d - 1);
5576 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5577 UPDATE_SYNTAX_TABLE (charpos);
5578 #endif
5579 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5580 s1 = SYNTAX (c1);
5581 #ifdef emacs
5582 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5583 #endif
5584 PREFETCH_NOLIMIT ();
5585 c2 = TARGET_CHAR_AND_LENGTH (d, dend - d, dummy);
5586 s2 = SYNTAX (c2);
5587
5588 if (/* Case 2: Only one of S1 and S2 is Sword. */
5589 ((s1 == Sword) != (s2 == Sword))
5590 /* Case 3: Both of S1 and S2 are Sword, and macro
5591 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5592 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5593 not = !not;
5594 }
5595 if (not)
5596 break;
5597 else
5598 goto fail;
5599
5600 case wordbeg:
5601 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5602
5603 /* We FAIL in one of the following cases: */
5604
5605 /* Case 1: D is at the end of string. */
5606 if (AT_STRINGS_END (d))
5607 goto fail;
5608 else
5609 {
5610 /* C1 is the character before D, S1 is the syntax of C1, C2
5611 is the character at D, and S2 is the syntax of C2. */
5612 re_wchar_t c1, c2;
5613 int s1, s2;
5614 int dummy;
5615 #ifdef emacs
5616 int offset = PTR_TO_OFFSET (d);
5617 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5618 UPDATE_SYNTAX_TABLE (charpos);
5619 #endif
5620 PREFETCH ();
5621 c2 = TARGET_CHAR_AND_LENGTH (d, dend - d, dummy);
5622 s2 = SYNTAX (c2);
5623
5624 /* Case 2: S2 is not Sword. */
5625 if (s2 != Sword)
5626 goto fail;
5627
5628 /* Case 3: D is not at the beginning of string ... */
5629 if (!AT_STRINGS_BEG (d))
5630 {
5631 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5632 #ifdef emacs
5633 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5634 #endif
5635 s1 = SYNTAX (c1);
5636
5637 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5638 returns 0. */
5639 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5640 goto fail;
5641 }
5642 }
5643 break;
5644
5645 case wordend:
5646 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5647
5648 /* We FAIL in one of the following cases: */
5649
5650 /* Case 1: D is at the beginning of string. */
5651 if (AT_STRINGS_BEG (d))
5652 goto fail;
5653 else
5654 {
5655 /* C1 is the character before D, S1 is the syntax of C1, C2
5656 is the character at D, and S2 is the syntax of C2. */
5657 re_wchar_t c1, c2;
5658 int s1, s2;
5659 int dummy;
5660 #ifdef emacs
5661 int offset = PTR_TO_OFFSET (d) - 1;
5662 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5663 UPDATE_SYNTAX_TABLE (charpos);
5664 #endif
5665 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5666 s1 = SYNTAX (c1);
5667
5668 /* Case 2: S1 is not Sword. */
5669 if (s1 != Sword)
5670 goto fail;
5671
5672 /* Case 3: D is not at the end of string ... */
5673 if (!AT_STRINGS_END (d))
5674 {
5675 PREFETCH_NOLIMIT ();
5676 c2 = TARGET_CHAR_AND_LENGTH (d, dend - d, dummy);
5677 #ifdef emacs
5678 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5679 #endif
5680 s2 = SYNTAX (c2);
5681
5682 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5683 returns 0. */
5684 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5685 goto fail;
5686 }
5687 }
5688 break;
5689
5690 case syntaxspec:
5691 case notsyntaxspec:
5692 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
5693 mcnt = *p++;
5694 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
5695 PREFETCH ();
5696 #ifdef emacs
5697 {
5698 int offset = PTR_TO_OFFSET (d);
5699 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5700 UPDATE_SYNTAX_TABLE (pos1);
5701 }
5702 #endif
5703 {
5704 int len;
5705 re_wchar_t c;
5706
5707 c = TARGET_CHAR_AND_LENGTH (d, dend - d, len);
5708 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
5709 goto fail;
5710 d += len;
5711 }
5712 break;
5713
5714 #ifdef emacs
5715 case before_dot:
5716 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5717 if (PTR_BYTE_POS (d) >= PT_BYTE)
5718 goto fail;
5719 break;
5720
5721 case at_dot:
5722 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5723 if (PTR_BYTE_POS (d) != PT_BYTE)
5724 goto fail;
5725 break;
5726
5727 case after_dot:
5728 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5729 if (PTR_BYTE_POS (d) <= PT_BYTE)
5730 goto fail;
5731 break;
5732
5733 case categoryspec:
5734 case notcategoryspec:
5735 not = (re_opcode_t) *(p - 1) == notcategoryspec;
5736 mcnt = *p++;
5737 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
5738 PREFETCH ();
5739 {
5740 int len;
5741 re_wchar_t c;
5742
5743 c = TARGET_CHAR_AND_LENGTH (d, dend - d, len);
5744
5745 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
5746 goto fail;
5747 d += len;
5748 }
5749 break;
5750
5751 #endif /* emacs */
5752
5753 default:
5754 abort ();
5755 }
5756 continue; /* Successfully executed one pattern command; keep going. */
5757
5758
5759 /* We goto here if a matching operation fails. */
5760 fail:
5761 IMMEDIATE_QUIT_CHECK;
5762 if (!FAIL_STACK_EMPTY ())
5763 {
5764 re_char *str, *pat;
5765 /* A restart point is known. Restore to that state. */
5766 DEBUG_PRINT1 ("\nFAIL:\n");
5767 POP_FAILURE_POINT (str, pat);
5768 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5769 {
5770 case on_failure_keep_string_jump:
5771 assert (str == NULL);
5772 goto continue_failure_jump;
5773
5774 case on_failure_jump_nastyloop:
5775 assert ((re_opcode_t)pat[-2] == no_op);
5776 PUSH_FAILURE_POINT (pat - 2, str);
5777 /* Fallthrough */
5778
5779 case on_failure_jump_loop:
5780 case on_failure_jump:
5781 case succeed_n:
5782 d = str;
5783 continue_failure_jump:
5784 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5785 p = pat + mcnt;
5786 break;
5787
5788 case no_op:
5789 /* A special frame used for nastyloops. */
5790 goto fail;
5791
5792 default:
5793 abort();
5794 }
5795
5796 assert (p >= bufp->buffer && p <= pend);
5797
5798 if (d >= string1 && d <= end1)
5799 dend = end_match_1;
5800 }
5801 else
5802 break; /* Matching at this starting point really fails. */
5803 } /* for (;;) */
5804
5805 if (best_regs_set)
5806 goto restore_best_regs;
5807
5808 FREE_VARIABLES ();
5809
5810 return -1; /* Failure to match. */
5811 } /* re_match_2 */
5812 \f
5813 /* Subroutine definitions for re_match_2. */
5814
5815 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5816 bytes; nonzero otherwise. */
5817
5818 static int
5819 bcmp_translate (s1, s2, len, translate, target_multibyte)
5820 re_char *s1, *s2;
5821 register int len;
5822 RE_TRANSLATE_TYPE translate;
5823 const int target_multibyte;
5824 {
5825 register re_char *p1 = s1, *p2 = s2;
5826 re_char *p1_end = s1 + len;
5827 re_char *p2_end = s2 + len;
5828
5829 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5830 different lengths, but relying on a single `len' would break this. -sm */
5831 while (p1 < p1_end && p2 < p2_end)
5832 {
5833 int p1_charlen, p2_charlen;
5834 re_wchar_t p1_ch, p2_ch;
5835
5836 p1_ch = TARGET_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5837 p2_ch = TARGET_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5838
5839 if (RE_TRANSLATE (translate, p1_ch)
5840 != RE_TRANSLATE (translate, p2_ch))
5841 return 1;
5842
5843 p1 += p1_charlen, p2 += p2_charlen;
5844 }
5845
5846 if (p1 != p1_end || p2 != p2_end)
5847 return 1;
5848
5849 return 0;
5850 }
5851 \f
5852 /* Entry points for GNU code. */
5853
5854 /* re_compile_pattern is the GNU regular expression compiler: it
5855 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5856 Returns 0 if the pattern was valid, otherwise an error string.
5857
5858 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5859 are set in BUFP on entry.
5860
5861 We call regex_compile to do the actual compilation. */
5862
5863 const char *
5864 re_compile_pattern (pattern, length, bufp)
5865 const char *pattern;
5866 size_t length;
5867 struct re_pattern_buffer *bufp;
5868 {
5869 reg_errcode_t ret;
5870
5871 /* GNU code is written to assume at least RE_NREGS registers will be set
5872 (and at least one extra will be -1). */
5873 bufp->regs_allocated = REGS_UNALLOCATED;
5874
5875 /* And GNU code determines whether or not to get register information
5876 by passing null for the REGS argument to re_match, etc., not by
5877 setting no_sub. */
5878 bufp->no_sub = 0;
5879
5880 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
5881
5882 if (!ret)
5883 return NULL;
5884 return gettext (re_error_msgid[(int) ret]);
5885 }
5886 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
5887 \f
5888 /* Entry points compatible with 4.2 BSD regex library. We don't define
5889 them unless specifically requested. */
5890
5891 #if defined _REGEX_RE_COMP || defined _LIBC
5892
5893 /* BSD has one and only one pattern buffer. */
5894 static struct re_pattern_buffer re_comp_buf;
5895
5896 char *
5897 # ifdef _LIBC
5898 /* Make these definitions weak in libc, so POSIX programs can redefine
5899 these names if they don't use our functions, and still use
5900 regcomp/regexec below without link errors. */
5901 weak_function
5902 # endif
5903 re_comp (s)
5904 const char *s;
5905 {
5906 reg_errcode_t ret;
5907
5908 if (!s)
5909 {
5910 if (!re_comp_buf.buffer)
5911 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5912 return (char *) gettext ("No previous regular expression");
5913 return 0;
5914 }
5915
5916 if (!re_comp_buf.buffer)
5917 {
5918 re_comp_buf.buffer = (unsigned char *) malloc (200);
5919 if (re_comp_buf.buffer == NULL)
5920 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5921 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5922 re_comp_buf.allocated = 200;
5923
5924 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5925 if (re_comp_buf.fastmap == NULL)
5926 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5927 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5928 }
5929
5930 /* Since `re_exec' always passes NULL for the `regs' argument, we
5931 don't need to initialize the pattern buffer fields which affect it. */
5932
5933 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5934
5935 if (!ret)
5936 return NULL;
5937
5938 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5939 return (char *) gettext (re_error_msgid[(int) ret]);
5940 }
5941
5942
5943 int
5944 # ifdef _LIBC
5945 weak_function
5946 # endif
5947 re_exec (s)
5948 const char *s;
5949 {
5950 const int len = strlen (s);
5951 return
5952 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5953 }
5954 #endif /* _REGEX_RE_COMP */
5955 \f
5956 /* POSIX.2 functions. Don't define these for Emacs. */
5957
5958 #ifndef emacs
5959
5960 /* regcomp takes a regular expression as a string and compiles it.
5961
5962 PREG is a regex_t *. We do not expect any fields to be initialized,
5963 since POSIX says we shouldn't. Thus, we set
5964
5965 `buffer' to the compiled pattern;
5966 `used' to the length of the compiled pattern;
5967 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5968 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5969 RE_SYNTAX_POSIX_BASIC;
5970 `fastmap' to an allocated space for the fastmap;
5971 `fastmap_accurate' to zero;
5972 `re_nsub' to the number of subexpressions in PATTERN.
5973
5974 PATTERN is the address of the pattern string.
5975
5976 CFLAGS is a series of bits which affect compilation.
5977
5978 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5979 use POSIX basic syntax.
5980
5981 If REG_NEWLINE is set, then . and [^...] don't match newline.
5982 Also, regexec will try a match beginning after every newline.
5983
5984 If REG_ICASE is set, then we considers upper- and lowercase
5985 versions of letters to be equivalent when matching.
5986
5987 If REG_NOSUB is set, then when PREG is passed to regexec, that
5988 routine will report only success or failure, and nothing about the
5989 registers.
5990
5991 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5992 the return codes and their meanings.) */
5993
5994 int
5995 regcomp (preg, pattern, cflags)
5996 regex_t *__restrict preg;
5997 const char *__restrict pattern;
5998 int cflags;
5999 {
6000 reg_errcode_t ret;
6001 reg_syntax_t syntax
6002 = (cflags & REG_EXTENDED) ?
6003 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6004
6005 /* regex_compile will allocate the space for the compiled pattern. */
6006 preg->buffer = 0;
6007 preg->allocated = 0;
6008 preg->used = 0;
6009
6010 /* Try to allocate space for the fastmap. */
6011 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6012
6013 if (cflags & REG_ICASE)
6014 {
6015 unsigned i;
6016
6017 preg->translate
6018 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6019 * sizeof (*(RE_TRANSLATE_TYPE)0));
6020 if (preg->translate == NULL)
6021 return (int) REG_ESPACE;
6022
6023 /* Map uppercase characters to corresponding lowercase ones. */
6024 for (i = 0; i < CHAR_SET_SIZE; i++)
6025 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6026 }
6027 else
6028 preg->translate = NULL;
6029
6030 /* If REG_NEWLINE is set, newlines are treated differently. */
6031 if (cflags & REG_NEWLINE)
6032 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6033 syntax &= ~RE_DOT_NEWLINE;
6034 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6035 }
6036 else
6037 syntax |= RE_NO_NEWLINE_ANCHOR;
6038
6039 preg->no_sub = !!(cflags & REG_NOSUB);
6040
6041 /* POSIX says a null character in the pattern terminates it, so we
6042 can use strlen here in compiling the pattern. */
6043 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6044
6045 /* POSIX doesn't distinguish between an unmatched open-group and an
6046 unmatched close-group: both are REG_EPAREN. */
6047 if (ret == REG_ERPAREN)
6048 ret = REG_EPAREN;
6049
6050 if (ret == REG_NOERROR && preg->fastmap)
6051 { /* Compute the fastmap now, since regexec cannot modify the pattern
6052 buffer. */
6053 re_compile_fastmap (preg);
6054 if (preg->can_be_null)
6055 { /* The fastmap can't be used anyway. */
6056 free (preg->fastmap);
6057 preg->fastmap = NULL;
6058 }
6059 }
6060 return (int) ret;
6061 }
6062 WEAK_ALIAS (__regcomp, regcomp)
6063
6064
6065 /* regexec searches for a given pattern, specified by PREG, in the
6066 string STRING.
6067
6068 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6069 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6070 least NMATCH elements, and we set them to the offsets of the
6071 corresponding matched substrings.
6072
6073 EFLAGS specifies `execution flags' which affect matching: if
6074 REG_NOTBOL is set, then ^ does not match at the beginning of the
6075 string; if REG_NOTEOL is set, then $ does not match at the end.
6076
6077 We return 0 if we find a match and REG_NOMATCH if not. */
6078
6079 int
6080 regexec (preg, string, nmatch, pmatch, eflags)
6081 const regex_t *__restrict preg;
6082 const char *__restrict string;
6083 size_t nmatch;
6084 regmatch_t pmatch[];
6085 int eflags;
6086 {
6087 int ret;
6088 struct re_registers regs;
6089 regex_t private_preg;
6090 int len = strlen (string);
6091 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6092
6093 private_preg = *preg;
6094
6095 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6096 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6097
6098 /* The user has told us exactly how many registers to return
6099 information about, via `nmatch'. We have to pass that on to the
6100 matching routines. */
6101 private_preg.regs_allocated = REGS_FIXED;
6102
6103 if (want_reg_info)
6104 {
6105 regs.num_regs = nmatch;
6106 regs.start = TALLOC (nmatch * 2, regoff_t);
6107 if (regs.start == NULL)
6108 return (int) REG_NOMATCH;
6109 regs.end = regs.start + nmatch;
6110 }
6111
6112 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6113 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6114 was a little bit longer but still only matching the real part.
6115 This works because the `endline' will check for a '\n' and will find a
6116 '\0', correctly deciding that this is not the end of a line.
6117 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6118 a convenient '\0' there. For all we know, the string could be preceded
6119 by '\n' which would throw things off. */
6120
6121 /* Perform the searching operation. */
6122 ret = re_search (&private_preg, string, len,
6123 /* start: */ 0, /* range: */ len,
6124 want_reg_info ? &regs : (struct re_registers *) 0);
6125
6126 /* Copy the register information to the POSIX structure. */
6127 if (want_reg_info)
6128 {
6129 if (ret >= 0)
6130 {
6131 unsigned r;
6132
6133 for (r = 0; r < nmatch; r++)
6134 {
6135 pmatch[r].rm_so = regs.start[r];
6136 pmatch[r].rm_eo = regs.end[r];
6137 }
6138 }
6139
6140 /* If we needed the temporary register info, free the space now. */
6141 free (regs.start);
6142 }
6143
6144 /* We want zero return to mean success, unlike `re_search'. */
6145 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6146 }
6147 WEAK_ALIAS (__regexec, regexec)
6148
6149
6150 /* Returns a message corresponding to an error code, ERRCODE, returned
6151 from either regcomp or regexec. We don't use PREG here. */
6152
6153 size_t
6154 regerror (errcode, preg, errbuf, errbuf_size)
6155 int errcode;
6156 const regex_t *preg;
6157 char *errbuf;
6158 size_t errbuf_size;
6159 {
6160 const char *msg;
6161 size_t msg_size;
6162
6163 if (errcode < 0
6164 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6165 /* Only error codes returned by the rest of the code should be passed
6166 to this routine. If we are given anything else, or if other regex
6167 code generates an invalid error code, then the program has a bug.
6168 Dump core so we can fix it. */
6169 abort ();
6170
6171 msg = gettext (re_error_msgid[errcode]);
6172
6173 msg_size = strlen (msg) + 1; /* Includes the null. */
6174
6175 if (errbuf_size != 0)
6176 {
6177 if (msg_size > errbuf_size)
6178 {
6179 strncpy (errbuf, msg, errbuf_size - 1);
6180 errbuf[errbuf_size - 1] = 0;
6181 }
6182 else
6183 strcpy (errbuf, msg);
6184 }
6185
6186 return msg_size;
6187 }
6188 WEAK_ALIAS (__regerror, regerror)
6189
6190
6191 /* Free dynamically allocated space used by PREG. */
6192
6193 void
6194 regfree (preg)
6195 regex_t *preg;
6196 {
6197 if (preg->buffer != NULL)
6198 free (preg->buffer);
6199 preg->buffer = NULL;
6200
6201 preg->allocated = 0;
6202 preg->used = 0;
6203
6204 if (preg->fastmap != NULL)
6205 free (preg->fastmap);
6206 preg->fastmap = NULL;
6207 preg->fastmap_accurate = 0;
6208
6209 if (preg->translate != NULL)
6210 free (preg->translate);
6211 preg->translate = NULL;
6212 }
6213 WEAK_ALIAS (__regfree, regfree)
6214
6215 #endif /* not emacs */