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