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