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