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