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