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