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