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