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