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