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