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