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