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