root/rxstring/trunk/myregex.c

Revision 257, 158.0 kB (checked in by tapted, 4 years ago)

Initial import of rxstring to pub

  • Property svn:eol-style set to native
  • Property svn:keywords set to author date id revision url Rev Revision
Line 
1/* Extended regular expression matching and search library,
2   version 0.12.
3   (Implements POSIX draft P10003.2/D11.2, except for
4   internationalization features.)
5
6   Copyright (C) 1993 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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
21
22/* AIX requires this to be the first thing in the file. */
23#if defined (_AIX) && !defined (REGEX_MALLOC)
24  #pragma alloca
25#endif
26
27#define _GNU_SOURCE
28
29/* We need this for `regex.h', and perhaps for the Emacs include files.  */
30#include <sys/types.h>
31
32#ifdef HAVE_CONFIG_H
33#include "config.h"
34#endif
35
36/* The `emacs' switch turns on certain matching commands
37   that make sense only in Emacs. */
38#ifdef emacs
39
40#include "lisp.h"
41#include "buffer.h"
42#include "syntax.h"
43#include "regex.h"
44
45/* Emacs uses `NULL' as a predicate.  */
46#undef NULL
47
48#else  /* not emacs */
49
50/* We used to test for `BSTRING' here, but only GCC and Emacs define
51   `BSTRING', as far as I know, and neither of them use this code.  */
52/*#if HAVE_STRING_H || STDC_HEADERS */
53#include <string.h>
54#ifndef bcmp
55#define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
56#endif
57#ifndef bcopy
58#define bcopy(s, d, n)  memcpy ((d), (s), (n))
59#endif
60#ifndef bzero
61#define bzero(s, n)     memset ((s), 0, (n))
62#endif
63/*
64#else
65#include <strings.h>
66#endif
67*/
68/*#ifdef STDC_HEADERS*/
69#include <stdlib.h>
70/*
71#else
72char *malloc ();
73char *realloc ();
74#endif
75*/
76
77/* Define the syntax stuff for \<, \>, etc.  */
78
79/* This must be nonzero for the wordchar and notwordchar pattern
80   commands in re_match_2.  */
81#ifndef Sword
82#define Sword 1
83#endif
84
85#ifdef SYNTAX_TABLE
86
87extern char *re_syntax_table;
88
89#else /* not SYNTAX_TABLE */
90
91/* How many characters in the character set.  */
92#define CHAR_SET_SIZE 256
93
94static char re_syntax_table[CHAR_SET_SIZE];
95
96static void
97init_syntax_once ()
98{
99   register int c;
100   static int done = 0;
101
102   if (done)
103     return;
104
105   bzero (re_syntax_table, sizeof re_syntax_table);
106
107   for (c = 'a'; c <= 'z'; c++)
108     re_syntax_table[c] = Sword;
109
110   for (c = 'A'; c <= 'Z'; c++)
111     re_syntax_table[c] = Sword;
112
113   for (c = '0'; c <= '9'; c++)
114     re_syntax_table[c] = Sword;
115
116   re_syntax_table['_'] = Sword;
117
118   done = 1;
119}
120
121#endif /* not SYNTAX_TABLE */
122
123#define SYNTAX(c) re_syntax_table[c]
124
125#endif /* not emacs */
126
127/* Get the interface, including the syntax bits.  */
128#include "myregex.h"
129
130/* isalpha etc. are used for the character classes.  */
131#include <ctype.h>
132
133#ifndef isascii
134#define isascii(c) 1
135#endif
136
137#ifdef isblank
138#define ISBLANK(c) (isascii (c) && isblank (c))
139#else
140#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
141#endif
142#ifdef isgraph
143#define ISGRAPH(c) (isascii (c) && isgraph (c))
144#else
145#define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
146#endif
147
148#define ISPRINT(c) (isascii (c) && isprint (c))
149#define ISDIGIT(c) (isascii (c) && isdigit (c))
150#define ISALNUM(c) (isascii (c) && isalnum (c))
151#define ISALPHA(c) (isascii (c) && isalpha (c))
152#define ISCNTRL(c) (isascii (c) && iscntrl (c))
153#define ISLOWER(c) (isascii (c) && islower (c))
154#define ISPUNCT(c) (isascii (c) && ispunct (c))
155#define ISSPACE(c) (isascii (c) && isspace (c))
156#define ISUPPER(c) (isascii (c) && isupper (c))
157#define ISXDIGIT(c) (isascii (c) && isxdigit (c))
158
159#ifndef NULL
160#define NULL 0
161#endif
162
163/* We remove any previous definition of `SIGN_EXTEND_CHAR',
164   since ours (we hope) works properly with all combinations of
165   machines, compilers, `char' and `unsigned char' argument types.
166   (Per Bothner suggested the basic approach.)  */
167#undef SIGN_EXTEND_CHAR
168#if __STDC__
169#define SIGN_EXTEND_CHAR(c) ((signed char) (c))
170#else  /* not __STDC__ */
171/* As in Harbison and Steele.  */
172#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
173#endif
174
175/* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
176   use `alloca' instead of `malloc'.  This is because using malloc in
177   re_search* or re_match* could cause memory leaks when C-g is used in
178   Emacs; also, malloc is slower and causes storage fragmentation.  On
179   the other hand, malloc is more portable, and easier to debug. 
180   
181   Because we sometimes use alloca, some routines have to be macros,
182   not functions -- `alloca'-allocated space disappears at the end of the
183   function it is called in.  */
184
185#ifdef REGEX_MALLOC
186
187#define REGEX_ALLOCATE malloc
188#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
189
190#else /* not REGEX_MALLOC  */
191
192/* Emacs already defines alloca, sometimes.  */
193#ifndef alloca
194
195/* Make alloca work the best possible way.  */
196#ifdef __GNUC__
197#define alloca __builtin_alloca
198#else /* not __GNUC__ */
199#if HAVE_ALLOCA_H
200#include <alloca.h>
201#else /* not __GNUC__ or HAVE_ALLOCA_H */
202#ifndef _AIX /* Already did AIX, up at the top.  */
203char *alloca ();
204#endif /* not _AIX */
205#endif /* not HAVE_ALLOCA_H */ 
206#endif /* not __GNUC__ */
207
208#endif /* not alloca */
209
210#define REGEX_ALLOCATE alloca
211
212/* Assumes a `char *destination' variable.  */
213#define REGEX_REALLOCATE(source, osize, nsize)                          \
214  (destination = (char *) alloca (nsize),                               \
215   bcopy (source, destination, osize),                                  \
216   destination)
217
218#endif /* not REGEX_MALLOC */
219
220
221/* True if `size1' is non-NULL and PTR is pointing anywhere inside
222   `string1' or just past its end.  This works if PTR is NULL, which is
223   a good thing.  */
224#define FIRST_STRING_P(ptr)                                     \
225  (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
226
227/* (Re)Allocate N items of type T using malloc, or fail.  */
228#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
229#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
230#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
231
232#define BYTEWIDTH 8 /* In bits.  */
233
234#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
235
236#define MAX(a, b) ((a) > (b) ? (a) : (b))
237#define MIN(a, b) ((a) < (b) ? (a) : (b))
238
239typedef char boolean;
240#define false 0
241#define true 1
242
243/* These are the command codes that appear in compiled regular
244   expressions.  Some opcodes are followed by argument bytes.  A
245   command code can specify any interpretation whatsoever for its
246   arguments.  Zero bytes may appear in the compiled regular expression.
247
248   The value of `exactn' is needed in search.c (search_buffer) in Emacs.
249   So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
250   `exactn' we use here must also be 1.  */
251
252typedef enum
253{
254  no_op = 0,
255
256        /* Followed by one byte giving n, then by n literal bytes.  */
257  exactn = 1,
258
259        /* Matches any (more or less) character.  */
260  anychar,
261
262        /* Matches any one char belonging to specified set.  First
263           following byte is number of bitmap bytes.  Then come bytes
264           for a bitmap saying which chars are in.  Bits in each byte
265           are ordered low-bit-first.  A character is in the set if its
266           bit is 1.  A character too large to have a bit in the map is
267           automatically not in the set.  */
268  charset,
269
270        /* Same parameters as charset, but match any character that is
271           not one of those specified.  */
272  charset_not,
273
274        /* Start remembering the text that is matched, for storing in a
275           register.  Followed by one byte with the register number, in
276           the range 0 to one less than the pattern buffer's re_nsub
277           field.  Then followed by one byte with the number of groups
278           inner to this one.  (This last has to be part of the
279           start_memory only because we need it in the on_failure_jump
280           of re_match_2.)  */
281  start_memory,
282
283        /* Stop remembering the text that is matched and store it in a
284           memory register.  Followed by one byte with the register
285           number, in the range 0 to one less than `re_nsub' in the
286           pattern buffer, and one byte with the number of inner groups,
287           just like `start_memory'.  (We need the number of inner
288           groups here because we don't have any easy way of finding the
289           corresponding start_memory when we're at a stop_memory.)  */
290  stop_memory,
291
292        /* Match a duplicate of something remembered. Followed by one
293           byte containing the register number.  */
294  duplicate,
295
296        /* Fail unless at beginning of line.  */
297  begline,
298
299        /* Fail unless at end of line.  */
300  endline,
301
302        /* Succeeds if at beginning of buffer (if emacs) or at beginning
303           of string to be matched (if not).  */
304  begbuf,
305
306        /* Analogously, for end of buffer/string.  */
307  endbuf,
308 
309        /* Followed by two byte relative address to which to jump.  */
310  jump, 
311
312        /* Same as jump, but marks the end of an alternative.  */
313  jump_past_alt,
314
315        /* Followed by two-byte relative address of place to resume at
316           in case of failure.  */
317  on_failure_jump,
318       
319        /* Like on_failure_jump, but pushes a placeholder instead of the
320           current string position when executed.  */
321  on_failure_keep_string_jump,
322 
323        /* Throw away latest failure point and then jump to following
324           two-byte relative address.  */
325  pop_failure_jump,
326
327        /* Change to pop_failure_jump if know won't have to backtrack to
328           match; otherwise change to jump.  This is used to jump
329           back to the beginning of a repeat.  If what follows this jump
330           clearly won't match what the repeat does, such that we can be
331           sure that there is no use backtracking out of repetitions
332           already matched, then we change it to a pop_failure_jump.
333           Followed by two-byte address.  */
334  maybe_pop_jump,
335
336        /* Jump to following two-byte address, and push a dummy failure
337           point. This failure point will be thrown away if an attempt
338           is made to use it for a failure.  A `+' construct makes this
339           before the first repeat.  Also used as an intermediary kind
340           of jump when compiling an alternative.  */
341  dummy_failure_jump,
342
343        /* Push a dummy failure point and continue.  Used at the end of
344           alternatives.  */
345  push_dummy_failure,
346
347        /* Followed by two-byte relative address and two-byte number n.
348           After matching N times, jump to the address upon failure.  */
349  succeed_n,
350
351        /* Followed by two-byte relative address, and two-byte number n.
352           Jump to the address N times, then fail.  */
353  jump_n,
354
355        /* Set the following two-byte relative address to the
356           subsequent two-byte number.  The address *includes* the two
357           bytes of number.  */
358  set_number_at,
359
360  wordchar,     /* Matches any word-constituent character.  */
361  notwordchar,  /* Matches any char that is not a word-constituent.  */
362
363  wordbeg,      /* Succeeds if at word beginning.  */
364  wordend,      /* Succeeds if at word end.  */
365
366  wordbound,    /* Succeeds if at a word boundary.  */
367  notwordbound  /* Succeeds if not at a word boundary.  */
368
369#ifdef emacs
370  ,before_dot,  /* Succeeds if before point.  */
371  at_dot,       /* Succeeds if at point.  */
372  after_dot,    /* Succeeds if after point.  */
373
374        /* Matches any character whose syntax is specified.  Followed by
375           a byte which contains a syntax code, e.g., Sword.  */
376  syntaxspec,
377
378        /* Matches any character whose syntax is not that specified.  */
379  notsyntaxspec
380#endif /* emacs */
381} re_opcode_t;
382
383/* Common operations on the compiled pattern.  */
384
385/* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
386
387#define STORE_NUMBER(destination, number)                               \
388  do {                                                                  \
389    (destination)[0] = (number) & 0377;                                 \
390    (destination)[1] = (number) >> 8;                                   \
391  } while (0)
392
393/* Same as STORE_NUMBER, except increment DESTINATION to
394   the byte after where the number is stored.  Therefore, DESTINATION
395   must be an lvalue.  */
396
397#define STORE_NUMBER_AND_INCR(destination, number)                      \
398  do {                                                                  \
399    STORE_NUMBER (destination, number);                                 \
400    (destination) += 2;                                                 \
401  } while (0)
402
403/* Put into DESTINATION a number stored in two contiguous bytes starting
404   at SOURCE.  */
405
406#define EXTRACT_NUMBER(destination, source)                             \
407  do {                                                                  \
408    (destination) = *(source) & 0377;                                   \
409    (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;           \
410  } while (0)
411
412#ifdef DEBUG
413static void
414extract_number (dest, source)
415    int *dest;
416    unsigned char *source;
417{
418  int temp = SIGN_EXTEND_CHAR (*(source + 1)); 
419  *dest = *source & 0377;
420  *dest += temp << 8;
421}
422
423#ifndef EXTRACT_MACROS /* To debug the macros.  */
424#undef EXTRACT_NUMBER
425#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
426#endif /* not EXTRACT_MACROS */
427
428#endif /* DEBUG */
429
430/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
431   SOURCE must be an lvalue.  */
432
433#define EXTRACT_NUMBER_AND_INCR(destination, source)                    \
434  do {                                                                  \
435    EXTRACT_NUMBER (destination, source);                               \
436    (source) += 2;                                                      \
437  } while (0)
438
439#ifdef DEBUG
440static void
441extract_number_and_incr (destination, source)
442    int *destination;
443    unsigned char **source;
444{ 
445  extract_number (destination, *source);
446  *source += 2;
447}
448
449#ifndef EXTRACT_MACROS
450#undef EXTRACT_NUMBER_AND_INCR
451#define EXTRACT_NUMBER_AND_INCR(dest, src) \
452  extract_number_and_incr (&dest, &src)
453#endif /* not EXTRACT_MACROS */
454
455#endif /* DEBUG */
456
457/* If DEBUG is defined, Regex prints many voluminous messages about what
458   it is doing (if the variable `debug' is nonzero).  If linked with the
459   main program in `iregex.c', you can enter patterns and strings
460   interactively.  And if linked with the main program in `main.c' and
461   the other test files, you can run the already-written tests.  */
462
463#ifdef DEBUG
464
465/* We use standard I/O for debugging.  */
466#include <stdio.h>
467
468/* It is useful to test things that ``must'' be true when debugging.  */
469#include <assert.h>
470
471static int debug = 0;
472
473#define DEBUG_STATEMENT(e) e
474#define DEBUG_PRINT1(x) if (debug) printf (x)
475#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
476#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
477#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
478#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)                           \
479  if (debug) print_partial_compiled_pattern (s, e)
480#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)                  \
481  if (debug) print_double_string (w, s1, sz1, s2, sz2)
482
483
484extern void printchar ();
485
486/* Print the fastmap in human-readable form.  */
487
488void
489print_fastmap (fastmap)
490    char *fastmap;
491{
492  unsigned was_a_range = 0;
493  unsigned i = 0; 
494 
495  while (i < (1 << BYTEWIDTH))
496    {
497      if (fastmap[i++])
498        {
499          was_a_range = 0;
500          printchar (i - 1);
501          while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
502            {
503              was_a_range = 1;
504              i++;
505            }
506          if (was_a_range)
507            {
508              printf ("-");
509              printchar (i - 1);
510            }
511        }
512    }
513  putchar ('\n'); 
514}
515
516
517/* Print a compiled pattern string in human-readable form, starting at
518   the START pointer into it and ending just before the pointer END.  */
519
520void
521print_partial_compiled_pattern (start, end)
522    unsigned char *start;
523    unsigned char *end;
524{
525  int mcnt, mcnt2;
526  unsigned char *p = start;
527  unsigned char *pend = end;
528
529  if (start == NULL)
530    {
531      printf ("(null)\n");
532      return;
533    }
534   
535  /* Loop over pattern commands.  */
536  while (p < pend)
537    {
538      switch ((re_opcode_t) *p++)
539        {
540        case no_op:
541          printf ("/no_op");
542          break;
543
544        case exactn:
545          mcnt = *p++;
546          printf ("/exactn/%d", mcnt);
547          do
548            {
549              putchar ('/');
550              printchar (*p++);
551            }
552          while (--mcnt);
553          break;
554
555        case start_memory:
556          mcnt = *p++;
557          printf ("/start_memory/%d/%d", mcnt, *p++);
558          break;
559
560        case stop_memory:
561          mcnt = *p++;
562          printf ("/stop_memory/%d/%d", mcnt, *p++);
563          break;
564
565        case duplicate:
566          printf ("/duplicate/%d", *p++);
567          break;
568
569        case anychar:
570          printf ("/anychar");
571          break;
572
573        case charset:
574        case charset_not:
575          {
576            register int c;
577
578            printf ("/charset%s",
579                    (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
580           
581            assert (p + *p < pend);
582
583            for (c = 0; c < *p; c++)
584              {
585                unsigned bit;
586                unsigned char map_byte = p[1 + c];
587               
588                putchar ('/');
589
590                for (bit = 0; bit < BYTEWIDTH; bit++)
591                  if (map_byte & (1 << bit))
592                    printchar (c * BYTEWIDTH + bit);
593              }
594            p += 1 + *p;
595            break;
596          }
597
598        case begline:
599          printf ("/begline");
600          break;
601
602        case endline:
603          printf ("/endline");
604          break;
605
606        case on_failure_jump:
607          extract_number_and_incr (&mcnt, &p);
608          printf ("/on_failure_jump/0/%d", mcnt);
609          break;
610
611        case on_failure_keep_string_jump:
612          extract_number_and_incr (&mcnt, &p);
613          printf ("/on_failure_keep_string_jump/0/%d", mcnt);
614          break;
615
616        case dummy_failure_jump:
617          extract_number_and_incr (&mcnt, &p);
618          printf ("/dummy_failure_jump/0/%d", mcnt);
619          break;
620
621        case push_dummy_failure:
622          printf ("/push_dummy_failure");
623          break;
624         
625        case maybe_pop_jump:
626          extract_number_and_incr (&mcnt, &p);
627          printf ("/maybe_pop_jump/0/%d", mcnt);
628          break;
629
630        case pop_failure_jump:
631          extract_number_and_incr (&mcnt, &p);
632          printf ("/pop_failure_jump/0/%d", mcnt);
633          break;         
634         
635        case jump_past_alt:
636          extract_number_and_incr (&mcnt, &p);
637          printf ("/jump_past_alt/0/%d", mcnt);
638          break;         
639         
640        case jump:
641          extract_number_and_incr (&mcnt, &p);
642          printf ("/jump/0/%d", mcnt);
643          break;
644
645        case succeed_n:
646          extract_number_and_incr (&mcnt, &p);
647          extract_number_and_incr (&mcnt2, &p);
648          printf ("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
649          break;
650       
651        case jump_n:
652          extract_number_and_incr (&mcnt, &p);
653          extract_number_and_incr (&mcnt2, &p);
654          printf ("/jump_n/0/%d/0/%d", mcnt, mcnt2);
655          break;
656       
657        case set_number_at:
658          extract_number_and_incr (&mcnt, &p);
659          extract_number_and_incr (&mcnt2, &p);
660          printf ("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
661          break;
662       
663        case wordbound:
664          printf ("/wordbound");
665          break;
666
667        case notwordbound:
668          printf ("/notwordbound");
669          break;
670
671        case wordbeg:
672          printf ("/wordbeg");
673          break;
674         
675        case wordend:
676          printf ("/wordend");
677         
678#ifdef emacs
679        case before_dot:
680          printf ("/before_dot");
681          break;
682
683        case at_dot:
684          printf ("/at_dot");
685          break;
686
687        case after_dot:
688          printf ("/after_dot");
689          break;
690
691        case syntaxspec:
692          printf ("/syntaxspec");
693          mcnt = *p++;
694          printf ("/%d", mcnt);
695          break;
696         
697        case notsyntaxspec:
698          printf ("/notsyntaxspec");
699          mcnt = *p++;
700          printf ("/%d", mcnt);
701          break;
702#endif /* emacs */
703
704        case wordchar:
705          printf ("/wordchar");
706          break;
707         
708        case notwordchar:
709          printf ("/notwordchar");
710          break;
711
712        case begbuf:
713          printf ("/begbuf");
714          break;
715
716        case endbuf:
717          printf ("/endbuf");
718          break;
719
720        default:
721          printf ("?%d", *(p-1));
722        }
723    }
724  printf ("/\n");
725}
726
727
728void
729print_compiled_pattern (bufp)
730    struct re_pattern_buffer *bufp;
731{
732  unsigned char *buffer = bufp->buffer;
733
734  print_partial_compiled_pattern (buffer, buffer + bufp->used);
735  printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
736
737  if (bufp->fastmap_accurate && bufp->fastmap)
738    {
739      printf ("fastmap: ");
740      print_fastmap (bufp->fastmap);
741    }
742
743  printf ("re_nsub: %d\t", bufp->re_nsub);
744  printf ("regs_alloc: %d\t", bufp->regs_allocated);
745  printf ("can_be_null: %d\t", bufp->can_be_null);
746  printf ("newline_anchor: %d\n", bufp->newline_anchor);
747  printf ("no_sub: %d\t", bufp->no_sub);
748  printf ("not_bol: %d\t", bufp->not_bol);
749  printf ("not_eol: %d\t", bufp->not_eol);
750  printf ("syntax: %d\n", bufp->syntax);
751  /* Perhaps we should print the translate table?  */
752}
753
754
755void
756print_double_string (where, string1, size1, string2, size2)
757    const char *where;
758    const char *string1;
759    const char *string2;
760    int size1;
761    int size2;
762{
763  unsigned this_char;
764 
765  if (where == NULL)
766    printf ("(null)");
767  else
768    {
769      if (FIRST_STRING_P (where))
770        {
771          for (this_char = where - string1; this_char < size1; this_char++)
772            printchar (string1[this_char]);
773
774          where = string2;   
775        }
776
777      for (this_char = where - string2; this_char < size2; this_char++)
778        printchar (string2[this_char]);
779    }
780}
781
782#else /* not DEBUG */
783
784#undef assert
785#define assert(e)
786
787#define DEBUG_STATEMENT(e)
788#define DEBUG_PRINT1(x)
789#define DEBUG_PRINT2(x1, x2)
790#define DEBUG_PRINT3(x1, x2, x3)
791#define DEBUG_PRINT4(x1, x2, x3, x4)
792#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
793#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
794
795#endif /* not DEBUG */
796
797/* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
798   also be assigned to arbitrarily: each pattern buffer stores its own
799   syntax, so it can be changed between regex compilations.  */
800reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
801
802
803/* Specify the precise syntax of regexps for compilation.  This provides
804   for compatibility for various utilities which historically have
805   different, incompatible syntaxes.
806
807   The argument SYNTAX is a bit mask comprised of the various bits
808   defined in regex.h.  We return the old syntax.  */
809
810reg_syntax_t
811re_set_syntax (syntax)
812    reg_syntax_t syntax;
813{
814  reg_syntax_t ret = re_syntax_options;
815 
816  re_syntax_options = syntax;
817  return ret;
818}
819
820/* This table gives an error message for each of the error codes listed
821   in regex.h.  Obviously the order here has to be same as there.  */
822
823static const char *re_error_msg[] =
824  { NULL,                                       /* REG_NOERROR */
825    "No match",                                 /* REG_NOMATCH */
826    "Invalid regular expression",               /* REG_BADPAT */
827    "Invalid collation character",              /* REG_ECOLLATE */
828    "Invalid character class name",             /* REG_ECTYPE */
829    "Trailing backslash",                       /* REG_EESCAPE */
830    "Invalid back reference",                   /* REG_ESUBREG */
831    "Unmatched [ or [^",                        /* REG_EBRACK */
832    "Unmatched ( or \\(",                       /* REG_EPAREN */
833    "Unmatched \\{",                            /* REG_EBRACE */
834    "Invalid content of \\{\\}",                /* REG_BADBR */
835    "Invalid range end",                        /* REG_ERANGE */
836    "Memory exhausted",                         /* REG_ESPACE */
837    "Invalid preceding regular expression",     /* REG_BADRPT */
838    "Premature end of regular expression",      /* REG_EEND */
839    "Regular expression too big",               /* REG_ESIZE */
840    "Unmatched ) or \\)",                       /* REG_ERPAREN */
841  };
842
843/* Subroutine declarations and macros for regex_compile.  */
844
845static void store_op1 (), store_op2 ();
846static void insert_op1 (), insert_op2 ();
847static boolean at_begline_loc_p (), at_endline_loc_p ();
848static boolean group_in_compile_stack ();
849static reg_errcode_t compile_range ();
850
851/* Fetch the next character in the uncompiled pattern---translating it
852   if necessary.  Also cast from a signed character in the constant
853   string passed to us by the user to an unsigned char that we can use
854   as an array index (in, e.g., `translate').  */
855#define PATFETCH(c)                                                     \
856  do {if (p == pend) return REG_EEND;                                   \
857    c = (unsigned char) *p++;                                           \
858    if (translate) c = translate[c];                                    \
859  } while (0)
860
861/* Fetch the next character in the uncompiled pattern, with no
862   translation.  */
863#define PATFETCH_RAW(c)                                                 \
864  do {if (p == pend) return REG_EEND;                                   \
865    c = (unsigned char) *p++;                                           \
866  } while (0)
867
868/* Go backwards one character in the pattern.  */
869#define PATUNFETCH p--
870
871
872/* If `translate' is non-null, return translate[D], else just D.  We
873   cast the subscript to translate because some data is declared as
874   `char *', to avoid warnings when a string constant is passed.  But
875   when we use a character as a subscript we must make it unsigned.  */
876#define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
877
878
879/* Macros for outputting the compiled pattern into `buffer'.  */
880
881/* If the buffer isn't allocated when it comes in, use this.  */
882#define INIT_BUF_SIZE  32
883
884/* Make sure we have at least N more bytes of space in buffer.  */
885#define GET_BUFFER_SPACE(n)                                             \
886    while (b - bufp->buffer + (n) > bufp->allocated)                    \
887      EXTEND_BUFFER ()
888
889/* Make sure we have one more byte of buffer space and then add C to it.  */
890#define BUF_PUSH(c)                                                     \
891  do {                                                                  \
892    GET_BUFFER_SPACE (1);                                               \
893    *b++ = (unsigned char) (c);                                         \
894  } while (0)
895
896
897/* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
898#define BUF_PUSH_2(c1, c2)                                              \
899  do {                                                                  \
900    GET_BUFFER_SPACE (2);                                               \
901    *b++ = (unsigned char) (c1);                                        \
902    *b++ = (unsigned char) (c2);                                        \
903  } while (0)
904
905
906/* As with BUF_PUSH_2, except for three bytes.  */
907#define BUF_PUSH_3(c1, c2, c3)                                          \
908  do {                                                                  \
909    GET_BUFFER_SPACE (3);                                               \
910    *b++ = (unsigned char) (c1);                                        \
911    *b++ = (unsigned char) (c2);                                        \
912    *b++ = (unsigned char) (c3);                                        \
913  } while (0)
914
915
916/* Store a jump with opcode OP at LOC to location TO.  We store a
917   relative address offset by the three bytes the jump itself occupies.  */
918#define STORE_JUMP(op, loc, to) \
919  store_op1 (op, loc, (to) - (loc) - 3)
920
921/* Likewise, for a two-argument jump.  */
922#define STORE_JUMP2(op, loc, to, arg) \
923  store_op2 (op, loc, (to) - (loc) - 3, arg)
924
925/* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
926#define INSERT_JUMP(op, loc, to) \
927  insert_op1 (op, loc, (to) - (loc) - 3, b)
928
929/* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
930#define INSERT_JUMP2(op, loc, to, arg) \
931  insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
932
933
934/* This is not an arbitrary limit: the arguments which represent offsets
935   into the pattern are two bytes long.  So if 2^16 bytes turns out to
936   be too small, many things would have to change.  */
937#define MAX_BUF_SIZE (1L << 16)
938
939
940/* Extend the buffer by twice its current size via realloc and
941   reset the pointers that pointed into the old block to point to the
942   correct places in the new one.  If extending the buffer results in it
943   being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
944#define EXTEND_BUFFER()                                                 \
945  do {                                                                  \
946    unsigned char *old_buffer = bufp->buffer;                           \
947    if (bufp->allocated == MAX_BUF_SIZE)                                \
948      return REG_ESIZE;                                                 \
949    bufp->allocated <<= 1;                                              \
950    if (bufp->allocated > MAX_BUF_SIZE)                                 \
951      bufp->allocated = MAX_BUF_SIZE;                                   \
952    bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
953    if (bufp->buffer == NULL)                                           \
954      return REG_ESPACE;                                                \
955    /* If the buffer moved, move all the pointers into it.  */          \
956    if (old_buffer != bufp->buffer)                                     \
957      {                                                                 \
958        b = (b - old_buffer) + bufp->buffer;                            \
959        begalt = (begalt - old_buffer) + bufp->buffer;                  \
960        if (fixup_alt_jump)                                             \
961          fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
962        if (laststart)                                                  \
963          laststart = (laststart - old_buffer) + bufp->buffer;          \
964        if (pending_exact)                                              \
965          pending_exact = (pending_exact - old_buffer) + bufp->buffer;  \
966      }                                                                 \
967  } while (0)
968
969
970/* Since we have one byte reserved for the register number argument to
971   {start,stop}_memory, the maximum number of groups we can report
972   things about is what fits in that byte.  */
973#define MAX_REGNUM 255
974
975/* But patterns can have more than `MAX_REGNUM' registers.  We just
976   ignore the excess.  */
977typedef unsigned regnum_t;
978
979
980/* Macros for the compile stack.  */
981
982/* Since offsets can go either forwards or backwards, this type needs to
983   be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
984typedef int pattern_offset_t;
985
986typedef struct
987{
988  pattern_offset_t begalt_offset;
989  pattern_offset_t fixup_alt_jump;
990  pattern_offset_t inner_group_offset;
991  pattern_offset_t laststart_offset; 
992  regnum_t regnum;
993} compile_stack_elt_t;
994
995
996typedef struct
997{
998  compile_stack_elt_t *stack;
999  unsigned size;
1000  unsigned avail;                       /* Offset of next open position.  */
1001} compile_stack_type;
1002
1003
1004#define INIT_COMPILE_STACK_SIZE 32
1005
1006#define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
1007#define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
1008
1009/* The next available element.  */
1010#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1011
1012
1013/* Set the bit for character C in a list.  */
1014#define SET_LIST_BIT(c)                               \
1015  (b[((unsigned char) (c)) / BYTEWIDTH]               \
1016   |= 1 << (((unsigned char) c) % BYTEWIDTH))
1017
1018
1019/* Get the next unsigned number in the uncompiled pattern.  */
1020#define GET_UNSIGNED_NUMBER(num)                                        \
1021  { if (p != pend)                                                      \
1022     {                                                                  \
1023       PATFETCH (c);                                                    \
1024       while (ISDIGIT (c))                                              \
1025         {                                                              \
1026           if (num < 0)                                                 \
1027              num = 0;                                                  \
1028           num = num * 10 + c - '0';                                    \
1029           if (p == pend)                                               \
1030              break;                                                    \
1031           PATFETCH (c);                                                \
1032         }                                                              \
1033       }                                                                \
1034    }           
1035
1036#define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
1037
1038#define IS_CHAR_CLASS(string)                                           \
1039   (STREQ (string, "alpha") || STREQ (string, "upper")                  \
1040    || STREQ (string, "lower") || STREQ (string, "digit")               \
1041    || STREQ (string, "alnum") || STREQ (string, "xdigit")              \
1042    || STREQ (string, "space") || STREQ (string, "print")               \
1043    || STREQ (string, "punct") || STREQ (string, "graph")               \
1044    || STREQ (string, "cntrl") || STREQ (string, "blank"))
1045
1046/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1047   Returns one of error codes defined in `regex.h', or zero for success.
1048
1049   Assumes the `allocated' (and perhaps `buffer') and `translate'
1050   fields are set in BUFP on entry.
1051
1052   If it succeeds, results are put in BUFP (if it returns an error, the
1053   contents of BUFP are undefined):
1054     `buffer' is the compiled pattern;
1055     `syntax' is set to SYNTAX;
1056     `used' is set to the length of the compiled pattern;
1057     `fastmap_accurate' is zero;
1058     `re_nsub' is the number of subexpressions in PATTERN;
1059     `not_bol' and `not_eol' are zero;
1060   
1061   The `fastmap' and `newline_anchor' fields are neither
1062   examined nor set.  */
1063
1064static reg_errcode_t
1065regex_compile (pattern, size, syntax, bufp)
1066     const char *pattern;
1067     int size;
1068     reg_syntax_t syntax;
1069     struct re_pattern_buffer *bufp;
1070{
1071  /* We fetch characters from PATTERN here.  Even though PATTERN is
1072     `char *' (i.e., signed), we declare these variables as unsigned, so
1073     they can be reliably used as array indices.  */
1074  register unsigned char c, c1;
1075 
1076  /* A random tempory spot in PATTERN.  */
1077  const char *p1;
1078
1079  /* Points to the end of the buffer, where we should append.  */
1080  register unsigned char *b;
1081 
1082  /* Keeps track of unclosed groups.  */
1083  compile_stack_type compile_stack;
1084
1085  /* Points to the current (ending) position in the pattern.  */
1086  const char *p = pattern;
1087  const char *pend = pattern + size;
1088 
1089  /* How to translate the characters in the pattern.  */
1090  char *translate = bufp->translate;
1091
1092  /* Address of the count-byte of the most recently inserted `exactn'
1093     command.  This makes it possible to tell if a new exact-match
1094     character can be added to that command or if the character requires
1095     a new `exactn' command.  */
1096  unsigned char *pending_exact = 0;
1097
1098  /* Address of start of the most recently finished expression.
1099     This tells, e.g., postfix * where to find the start of its
1100     operand.  Reset at the beginning of groups and alternatives.  */
1101  unsigned char *laststart = 0;
1102
1103  /* Address of beginning of regexp, or inside of last group.  */
1104  unsigned char *begalt;
1105
1106  /* Place in the uncompiled pattern (i.e., the {) to
1107     which to go back if the interval is invalid.  */
1108  const char *beg_interval;
1109               
1110  /* Address of the place where a forward jump should go to the end of
1111     the containing expression.  Each alternative of an `or' -- except the
1112     last -- ends with a forward jump of this sort.  */
1113  unsigned char *fixup_alt_jump = 0;
1114
1115  /* Counts open-groups as they are encountered.  Remembered for the
1116     matching close-group on the compile stack, so the same register
1117     number is put in the stop_memory as the start_memory.  */
1118  regnum_t regnum = 0;
1119
1120#ifdef DEBUG
1121  DEBUG_PRINT1 ("\nCompiling pattern: ");
1122  if (debug)
1123    {
1124      unsigned debug_count;
1125     
1126      for (debug_count = 0; debug_count < size; debug_count++)
1127        printchar (pattern[debug_count]);
1128      putchar ('\n');
1129    }
1130#endif /* DEBUG */
1131
1132  /* Initialize the compile stack.  */
1133  compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1134  if (compile_stack.stack == NULL)
1135    return REG_ESPACE;
1136
1137  compile_stack.size = INIT_COMPILE_STACK_SIZE;
1138  compile_stack.avail = 0;
1139
1140  /* Initialize the pattern buffer.  */
1141  bufp->syntax = syntax;
1142  bufp->fastmap_accurate = 0;
1143  bufp->not_bol = bufp->not_eol = 0;
1144
1145  /* Set `used' to zero, so that if we return an error, the pattern
1146     printer (for debugging) will think there's no pattern.  We reset it
1147     at the end.  */
1148  bufp->used = 0;
1149 
1150  /* Always count groups, whether or not bufp->no_sub is set.  */
1151  bufp->re_nsub = 0;                           
1152
1153#if !defined (emacs) && !defined (SYNTAX_TABLE)
1154  /* Initialize the syntax table.  */
1155   init_syntax_once ();
1156#endif
1157
1158  if (bufp->allocated == 0)
1159    {
1160      if (bufp->buffer)
1161        { /* If zero allocated, but buffer is non-null, try to realloc
1162             enough space.  This loses if buffer's address is bogus, but
1163             that is the user's responsibility.  */
1164          RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1165        }
1166      else
1167        { /* Caller did not allocate a buffer.  Do it for them.  */
1168          bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1169        }
1170      if (!bufp->buffer) return REG_ESPACE;
1171
1172      bufp->allocated = INIT_BUF_SIZE;
1173    }
1174
1175  begalt = b = bufp->buffer;
1176
1177  /* Loop through the uncompiled pattern until we're at the end.  */
1178  while (p != pend)
1179    {
1180      PATFETCH (c);
1181
1182      switch (c)
1183        {
1184        case '^':
1185          {
1186            if (   /* If at start of pattern, it's an operator.  */
1187                   p == pattern + 1
1188                   /* If context independent, it's an operator.  */
1189                || syntax & RE_CONTEXT_INDEP_ANCHORS
1190                   /* Otherwise, depends on what's come before.  */
1191                || at_begline_loc_p (pattern, p, syntax))
1192              BUF_PUSH (begline);
1193            else
1194              goto normal_char;
1195          }
1196          break;
1197
1198
1199        case '$':
1200          {
1201            if (   /* If at end of pattern, it's an operator.  */
1202                   p == pend 
1203                   /* If context independent, it's an operator.  */
1204                || syntax & RE_CONTEXT_INDEP_ANCHORS
1205                   /* Otherwise, depends on what's next.  */
1206                || at_endline_loc_p (p, pend, syntax))
1207               BUF_PUSH (endline);
1208             else
1209               goto normal_char;
1210           }
1211           break;
1212
1213
1214        case '+':
1215        case '?':
1216          if ((syntax & RE_BK_PLUS_QM)
1217              || (syntax & RE_LIMITED_OPS))
1218            goto normal_char;
1219        handle_plus:
1220        case '*':
1221          /* If there is no previous pattern... */
1222          if (!laststart)
1223            {
1224              if (syntax & RE_CONTEXT_INVALID_OPS)
1225                return REG_BADRPT;
1226              else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1227                goto normal_char;
1228            }
1229
1230          {
1231            /* Are we optimizing this jump?  */
1232            boolean keep_string_p = false;
1233           
1234            /* 1 means zero (many) matches is allowed.  */
1235            char zero_times_ok = 0, many_times_ok = 0;
1236
1237            /* If there is a sequence of repetition chars, collapse it
1238               down to just one (the right one).  We can't combine
1239               interval operators with these because of, e.g., `a{2}*',
1240               which should only match an even number of `a's.  */
1241
1242            for (;;)
1243              {
1244                zero_times_ok |= c != '+';
1245                many_times_ok |= c != '?';
1246
1247                if (p == pend)
1248                  break;
1249
1250                PATFETCH (c);
1251
1252                if (c == '*'
1253                    || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1254                  ;
1255
1256                else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
1257                  {
1258                    if (p == pend) return REG_EESCAPE;
1259
1260                    PATFETCH (c1);
1261                    if (!(c1 == '+' || c1 == '?'))
1262                      {
1263                        PATUNFETCH;
1264                        PATUNFETCH;
1265                        break;
1266                      }
1267
1268                    c = c1;
1269                  }
1270                else
1271                  {
1272                    PATUNFETCH;
1273                    break;
1274                  }
1275
1276                /* If we get here, we found another repeat character.  */
1277               }
1278
1279            /* Star, etc. applied to an empty pattern is equivalent
1280               to an empty pattern.  */
1281            if (!laststart) 
1282              break;
1283
1284            /* Now we know whether or not zero matches is allowed
1285               and also whether or not two or more matches is allowed.  */
1286            if (many_times_ok)
1287              { /* More than one repetition is allowed, so put in at the
1288                   end a backward relative jump from `b' to before the next
1289                   jump we're going to put in below (which jumps from
1290                   laststart to after this jump). 
1291
1292                   But if we are at the `*' in the exact sequence `.*\n',
1293                   insert an unconditional jump backwards to the .,
1294                   instead of the beginning of the loop.  This way we only
1295                   push a failure point once, instead of every time
1296                   through the loop.  */
1297                assert (p - 1 > pattern);
1298
1299                /* Allocate the space for the jump.  */
1300                GET_BUFFER_SPACE (3);
1301
1302                /* We know we are not at the first character of the pattern,
1303                   because laststart was nonzero.  And we've already
1304                   incremented `p', by the way, to be the character after
1305                   the `*'.  Do we have to do something analogous here
1306                   for null bytes, because of RE_DOT_NOT_NULL?  */
1307                if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1308                    && zero_times_ok
1309                    && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1310                    && !(syntax & RE_DOT_NEWLINE))
1311                  { /* We have .*\n.  */
1312                    STORE_JUMP (jump, b, laststart);
1313                    keep_string_p = true;
1314                  }
1315                else
1316                  /* Anything else.  */
1317                  STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1318
1319                /* We've added more stuff to the buffer.  */
1320                b += 3;
1321              }
1322
1323            /* On failure, jump from laststart to b + 3, which will be the
1324               end of the buffer after this jump is inserted.  */
1325            GET_BUFFER_SPACE (3);
1326            INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1327                                       : on_failure_jump,
1328                         laststart, b + 3);
1329            pending_exact = 0;
1330            b += 3;
1331
1332            if (!zero_times_ok)
1333              {
1334                /* At least one repetition is required, so insert a
1335                   `dummy_failure_jump' before the initial
1336                   `on_failure_jump' instruction of the loop. This
1337                   effects a skip over that instruction the first time
1338                   we hit that loop.  */
1339                GET_BUFFER_SPACE (3);
1340                INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1341                b += 3;
1342              }
1343            }
1344          break;
1345
1346
1347        case '.':
1348          laststart = b;
1349          BUF_PUSH (anychar);
1350          break;
1351
1352
1353        case '[':
1354          {
1355            boolean had_char_class = false;
1356
1357            if (p == pend) return REG_EBRACK;
1358
1359            /* Ensure that we have enough space to push a charset: the
1360               opcode, the length count, and the bitset; 34 bytes in all.  */
1361            GET_BUFFER_SPACE (34);
1362
1363            laststart = b;
1364
1365            /* We test `*p == '^' twice, instead of using an if
1366               statement, so we only need one BUF_PUSH.  */
1367            BUF_PUSH (*p == '^' ? charset_not : charset); 
1368            if (*p == '^')
1369              p++;
1370
1371            /* Remember the first position in the bracket expression.  */
1372            p1 = p;
1373
1374            /* Push the number of bytes in the bitmap.  */
1375            BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1376
1377            /* Clear the whole map.  */
1378            bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1379
1380            /* charset_not matches newline according to a syntax bit.  */
1381            if ((re_opcode_t) b[-2] == charset_not
1382                && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1383              SET_LIST_BIT ('\n');
1384
1385            /* Read in characters and ranges, setting map bits.  */
1386            for (;;)
1387              {
1388                if (p == pend) return REG_EBRACK;
1389
1390                PATFETCH (c);
1391
1392                /* \ might escape characters inside [...] and [^...].  */
1393                if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1394                  {
1395                    if (p == pend) return REG_EESCAPE;
1396
1397                    PATFETCH (c1);
1398                    SET_LIST_BIT (c1);
1399                    continue;
1400                  }
1401
1402                /* Could be the end of the bracket expression.  If it's
1403                   not (i.e., when the bracket expression is `[]' so
1404                   far), the ']' character bit gets set way below.  */
1405                if (c == ']' && p != p1 + 1)
1406                  break;
1407
1408                /* Look ahead to see if it's a range when the last thing
1409                   was a character class.  */
1410                if (had_char_class && c == '-' && *p != ']')
1411                  return REG_ERANGE;
1412
1413                /* Look ahead to see if it's a range when the last thing
1414                   was a character: if this is a hyphen not at the
1415                   beginning or the end of a list, then it's the range
1416                   operator.  */
1417                if (c == '-' 
1418                    && !(p - 2 >= pattern && p[-2] == '[') 
1419                    && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1420                    && *p != ']')
1421                  {
1422                    reg_errcode_t ret
1423                      = compile_range (&p, pend, translate, syntax, b);
1424                    if (ret != REG_NOERROR) return ret;
1425                  }
1426
1427                else if (p[0] == '-' && p[1] != ']')
1428                  { /* This handles ranges made up of characters only.  */
1429                    reg_errcode_t ret;
1430
1431                    /* Move past the `-'.  */
1432                    PATFETCH (c1);
1433                   
1434                    ret = compile_range (&p, pend, translate, syntax, b);
1435                    if (ret != REG_NOERROR) return ret;
1436                  }
1437
1438                /* See if we're at the beginning of a possible character
1439                   class.  */
1440
1441                else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1442                  { /* Leave room for the null.  */
1443                    char str[CHAR_CLASS_MAX_LENGTH + 1];
1444
1445                    PATFETCH (c);
1446                    c1 = 0;
1447
1448                    /* If pattern is `[[:'.  */
1449                    if (p == pend) return REG_EBRACK;
1450
1451                    for (;;)
1452                      {
1453                        PATFETCH (c);
1454                        if (c == ':' || c == ']' || p == pend
1455                            || c1 == CHAR_CLASS_MAX_LENGTH)
1456                          break;
1457                        str[c1++] = c;
1458                      }
1459                    str[c1] = '\0';
1460
1461                    /* If isn't a word bracketed by `[:' and:`]':
1462                       undo the ending character, the letters, and leave
1463                       the leading `:' and `[' (but set bits for them).  */
1464                    if (c == ':' && *p == ']')
1465                      {
1466                        int ch;
1467                        boolean is_alnum = STREQ (str, "alnum");
1468                        boolean is_alpha = STREQ (str, "alpha");
1469                        boolean is_blank = STREQ (str, "blank");
1470                        boolean is_cntrl = STREQ (str, "cntrl");
1471                        boolean is_digit = STREQ (str, "digit");
1472                        boolean is_graph = STREQ (str, "graph");
1473                        boolean is_lower = STREQ (str, "lower");
1474                        boolean is_print = STREQ (str, "print");
1475                        boolean is_punct = STREQ (str, "punct");
1476                        boolean is_space = STREQ (str, "space");
1477                        boolean is_upper = STREQ (str, "upper");
1478                        boolean is_xdigit = STREQ (str, "xdigit");
1479                       
1480                        if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
1481
1482                        /* Throw away the ] at the end of the character
1483                           class.  */
1484                        PATFETCH (c);                                   
1485
1486                        if (p == pend) return REG_EBRACK;
1487
1488                        for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
1489                          {
1490                            if (   (is_alnum  && ISALNUM (ch))
1491                                || (is_alpha  && ISALPHA (ch))
1492                                || (is_blank  && ISBLANK (ch))
1493                                || (is_cntrl  && ISCNTRL (ch))
1494                                || (is_digit  && ISDIGIT (ch))
1495                                || (is_graph  && ISGRAPH (ch))
1496                                || (is_lower  && ISLOWER (ch))
1497                                || (is_print  && ISPRINT (ch))
1498                                || (is_punct  && ISPUNCT (ch))
1499                                || (is_space  && ISSPACE (ch))
1500                                || (is_upper  && ISUPPER (ch))
1501                                || (is_xdigit && ISXDIGIT (ch)))
1502                            SET_LIST_BIT (ch);
1503                          }
1504                        had_char_class = true;
1505                      }
1506                    else
1507                      {
1508                        c1++;
1509                        while (c1--)   
1510                          PATUNFETCH;
1511                        SET_LIST_BIT ('[');
1512                        SET_LIST_BIT (':');
1513                        had_char_class = false;
1514                      }
1515                  }
1516                else
1517                  {
1518                    had_char_class = false;
1519                    SET_LIST_BIT (c);
1520                  }
1521              }
1522
1523            /* Discard any (non)matching list bytes that are all 0 at the
1524               end of the map.  Decrease the map-length byte too.  */
1525            while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
1526              b[-1]--; 
1527            b += b[-1];
1528          }
1529          break;
1530
1531
1532        case '(':
1533          if (syntax & RE_NO_BK_PARENS)
1534            goto handle_open;
1535          else
1536            goto normal_char;
1537
1538
1539        case ')':
1540          if (syntax & RE_NO_BK_PARENS)
1541            goto handle_close;
1542          else
1543            goto normal_char;
1544
1545
1546        case '\n':
1547          if (syntax & RE_NEWLINE_ALT)
1548            goto handle_alt;
1549          else
1550            goto normal_char;
1551
1552
1553        case '|':
1554          if (syntax & RE_NO_BK_VBAR)
1555            goto handle_alt;
1556          else
1557            goto normal_char;
1558
1559
1560        case '{':
1561           if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1562             goto handle_interval;
1563           else
1564             goto normal_char;
1565
1566
1567        case '\\':
1568          if (p == pend) return REG_EESCAPE;
1569
1570          /* Do not translate the character after the \, so that we can
1571             distinguish, e.g., \B from \b, even if we normally would
1572             translate, e.g., B to b.  */
1573          PATFETCH_RAW (c);
1574
1575          switch (c)
1576            {
1577            case '(':
1578              if (syntax & RE_NO_BK_PARENS)
1579                goto normal_backslash;
1580
1581            handle_open:
1582              bufp->re_nsub++;
1583              regnum++;
1584
1585              if (COMPILE_STACK_FULL)
1586                { 
1587                  RETALLOC (compile_stack.stack, compile_stack.size << 1,
1588                            compile_stack_elt_t);
1589                  if (compile_stack.stack == NULL) return REG_ESPACE;
1590
1591                  compile_stack.size <<= 1;
1592                }
1593
1594              /* These are the values to restore when we hit end of this
1595                 group.  They are all relative offsets, so that if the
1596                 whole pattern moves because of realloc, they will still
1597                 be valid.  */
1598              COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1599              COMPILE_STACK_TOP.fixup_alt_jump 
1600                = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1601              COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1602              COMPILE_STACK_TOP.regnum = regnum;
1603
1604              /* We will eventually replace the 0 with the number of
1605                 groups inner to this one.  But do not push a
1606                 start_memory for groups beyond the last one we can
1607                 represent in the compiled pattern.  */
1608              if (regnum <= MAX_REGNUM)
1609                {
1610                  COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1611                  BUF_PUSH_3 (start_memory, regnum, 0);
1612                }
1613               
1614              compile_stack.avail++;
1615
1616              fixup_alt_jump = 0;
1617              laststart = 0;
1618              begalt = b;
1619              /* If we've reached MAX_REGNUM groups, then this open
1620                 won't actually generate any code, so we'll have to
1621                 clear pending_exact explicitly.  */
1622              pending_exact = 0;
1623              break;
1624
1625
1626            case ')':
1627              if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
1628
1629              if (COMPILE_STACK_EMPTY)
1630                if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1631                  goto normal_backslash;
1632                else
1633                  return REG_ERPAREN;
1634
1635            handle_close:
1636              if (fixup_alt_jump)
1637                { /* Push a dummy failure point at the end of the
1638                     alternative for a possible future
1639                     `pop_failure_jump' to pop.  See comments at
1640                     `push_dummy_failure' in `re_match_2'.  */
1641                  BUF_PUSH (push_dummy_failure);
1642                 
1643                  /* We allocated space for this jump when we assigned
1644                     to `fixup_alt_jump', in the `handle_alt' case below.  */
1645                  STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
1646                }
1647
1648              /* See similar code for backslashed left paren above.  */
1649              if (COMPILE_STACK_EMPTY)
1650                if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1651                  goto normal_char;
1652                else
1653                  return REG_ERPAREN;
1654
1655              /* Since we just checked for an empty stack above, this
1656                 ``can't happen''.  */
1657              assert (compile_stack.avail != 0);
1658              {
1659                /* We don't just want to restore into `regnum', because
1660                   later groups should continue to be numbered higher,
1661                   as in `(ab)c(de)' -- the second group is #2.  */
1662                regnum_t this_group_regnum;
1663
1664                compile_stack.avail--;         
1665                begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1666                fixup_alt_jump
1667                  = COMPILE_STACK_TOP.fixup_alt_jump
1668                    ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 
1669                    : 0;
1670                laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1671                this_group_regnum = COMPILE_STACK_TOP.regnum;
1672                /* If we've reached MAX_REGNUM groups, then this open
1673                   won't actually generate any code, so we'll have to
1674                   clear pending_exact explicitly.  */
1675                pending_exact = 0;
1676
1677                /* We're at the end of the group, so now we know how many
1678                   groups were inside this one.  */
1679                if (this_group_regnum <= MAX_REGNUM)
1680                  {
1681                    unsigned char *inner_group_loc
1682                      = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1683                   
1684                    *inner_group_loc = regnum - this_group_regnum;
1685                    BUF_PUSH_3 (stop_memory, this_group_regnum,
1686                                regnum - this_group_regnum);
1687                  }
1688              }
1689              break;
1690
1691
1692            case '|':                                   /* `\|'.  */
1693              if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1694                goto normal_backslash;
1695            handle_alt:
1696              if (syntax & RE_LIMITED_OPS)
1697                goto normal_char;
1698
1699              /* Insert before the previous alternative a jump which
1700                 jumps to this alternative if the former fails.  */
1701              GET_BUFFER_SPACE (3);
1702              INSERT_JUMP (on_failure_jump, begalt, b + 6);
1703              pending_exact = 0;
1704              b += 3;
1705
1706              /* The alternative before this one has a jump after it
1707                 which gets executed if it gets matched.  Adjust that
1708                 jump so it will jump to this alternative's analogous
1709                 jump (put in below, which in turn will jump to the next
1710                 (if any) alternative's such jump, etc.).  The last such
1711                 jump jumps to the correct final destination.  A picture:
1712                          _____ _____
1713                          |   | |   |   
1714                          |   v |   v
1715                         a | b   | c   
1716
1717                 If we are at `b', then fixup_alt_jump right now points to a
1718                 three-byte space after `a'.  We'll put in the jump, set
1719                 fixup_alt_jump to right after `b', and leave behind three
1720                 bytes which we'll fill in when we get to after `c'.  */
1721
1722              if (fixup_alt_jump)
1723                STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
1724
1725              /* Mark and leave space for a jump after this alternative,
1726                 to be filled in later either by next alternative or
1727                 when know we're at the end of a series of alternatives.  */
1728              fixup_alt_jump = b;
1729              GET_BUFFER_SPACE (3);
1730              b += 3;
1731
1732              laststart = 0;
1733              begalt = b;
1734              break;
1735
1736
1737            case '{':
1738              /* If \{ is a literal.  */
1739              if (!(syntax & RE_INTERVALS)
1740                     /* If we're at `\{' and it's not the open-interval
1741                        operator.  */
1742                  || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1743                  || (p - 2 == pattern  &&  p == pend))
1744                goto normal_backslash;
1745
1746            handle_interval:
1747              {
1748                /* If got here, then the syntax allows intervals.  */
1749
1750                /* At least (most) this many matches must be made.  */
1751                int lower_bound = -1, upper_bound = -1;
1752
1753                beg_interval = p - 1;
1754
1755                if (p == pend)
1756                  {
1757                    if (syntax & RE_NO_BK_BRACES)
1758                      goto unfetch_interval;
1759                    else
1760                      return REG_EBRACE;
1761                  }
1762
1763                GET_UNSIGNED_NUMBER (lower_bound);
1764
1765                if (c == ',')
1766                  {
1767                    GET_UNSIGNED_NUMBER (upper_bound);
1768                    if (upper_bound < 0) upper_bound = RE_DUP_MAX;
1769                  }
1770                else
1771                  /* Interval such as `{1}' => match exactly once. */
1772                  upper_bound = lower_bound;
1773
1774                if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1775                    || lower_bound > upper_bound)
1776                  {
1777                    if (syntax & RE_NO_BK_BRACES)
1778                      goto unfetch_interval;
1779                    else 
1780                      return REG_BADBR;
1781                  }
1782
1783                if (!(syntax & RE_NO_BK_BRACES)) 
1784                  {
1785                    if (c != '\\') return REG_EBRACE;
1786
1787                    PATFETCH (c);
1788                  }
1789
1790                if (c != '}')
1791                  {
1792                    if (syntax & RE_NO_BK_BRACES)
1793                      goto unfetch_interval;
1794                    else 
1795                      return REG_BADBR;
1796                  }
1797
1798                /* We just parsed a valid interval.  */
1799
1800                /* If it's invalid to have no preceding re.  */
1801                if (!laststart)
1802                  {
1803                    if (syntax & RE_CONTEXT_INVALID_OPS)
1804                      return REG_BADRPT;
1805                    else if (syntax & RE_CONTEXT_INDEP_OPS)
1806                      laststart = b;
1807                    else
1808                      goto unfetch_interval;
1809                  }
1810
1811                /* If the upper bound is zero, don't want to succeed at
1812                   all; jump from `laststart' to `b + 3', which will be
1813                   the end of the buffer after we insert the jump.  */
1814                 if (upper_bound == 0)
1815                   {
1816                     GET_BUFFER_SPACE (3);
1817                     INSERT_JUMP (jump, laststart, b + 3);
1818                     b += 3;
1819                   }
1820
1821                 /* Otherwise, we have a nontrivial interval.  When
1822                    we're all done, the pattern will look like:
1823                      set_number_at <jump count> <upper bound>
1824                      set_number_at <succeed_n count> <lower bound>
1825                      succeed_n <after jump addr> <succed_n count>
1826                      <body of loop>
1827                      jump_n <succeed_n addr> <jump count>
1828                    (The upper bound and `jump_n' are omitted if
1829                    `upper_bound' is 1, though.)  */
1830                 else 
1831                   { /* If the upper bound is > 1, we need to insert
1832                        more at the end of the loop.  */
1833                     unsigned nbytes = 10 + (upper_bound > 1) * 10;
1834
1835                     GET_BUFFER_SPACE (nbytes);
1836
1837                     /* Initialize lower bound of the `succeed_n', even
1838                        though it will be set during matching by its
1839                        attendant `set_number_at' (inserted next),
1840                        because `re_compile_fastmap' needs to know.
1841                        Jump to the `jump_n' we might insert below.  */
1842                     INSERT_JUMP2 (succeed_n, laststart,
1843                                   b + 5 + (upper_bound > 1) * 5,
1844                                   lower_bound);
1845                     b += 5;
1846
1847                     /* Code to initialize the lower bound.  Insert
1848                        before the `succeed_n'.  The `5' is the last two
1849                        bytes of this `set_number_at', plus 3 bytes of
1850                        the following `succeed_n'.  */
1851                     insert_op2 (set_number_at, laststart, 5, lower_bound, b);
1852                     b += 5;
1853
1854                     if (upper_bound > 1)
1855                       { /* More than one repetition is allowed, so
1856                            append a backward jump to the `succeed_n'
1857                            that starts this interval.
1858                           
1859                            When we've reached this during matching,
1860                            we'll have matched the interval once, so
1861                            jump back only `upper_bound - 1' times.  */
1862                         STORE_JUMP2 (jump_n, b, laststart + 5,
1863                                      upper_bound - 1);
1864                         b += 5;
1865
1866                         /* The location we want to set is the second
1867                            parameter of the `jump_n'; that is `b-2' as
1868                            an absolute address.  `laststart' will be
1869                            the `set_number_at' we're about to insert;
1870                            `laststart+3' the number to set, the source
1871                            for the relative address.  But we are
1872                            inserting into the middle of the pattern --
1873                            so everything is getting moved up by 5.
1874                            Conclusion: (b - 2) - (laststart + 3) + 5,
1875                            i.e., b - laststart.
1876                           
1877                            We insert this at the beginning of the loop
1878                            so that if we fail during matching, we'll
1879                            reinitialize the bounds.  */
1880                         insert_op2 (set_number_at, laststart, b - laststart,
1881                                     upper_bound - 1, b);
1882                         b += 5;
1883                       }
1884                   }
1885                pending_exact = 0;
1886                beg_interval = NULL;
1887              }
1888              break;
1889
1890            unfetch_interval:
1891              /* If an invalid interval, match the characters as literals.  */
1892               assert (beg_interval);
1893               p = beg_interval;
1894               beg_interval = NULL;
1895
1896               /* normal_char and normal_backslash need `c'.  */
1897               PATFETCH (c);   
1898
1899               if (!(syntax & RE_NO_BK_BRACES))
1900                 {
1901                   if (p > pattern  &&  p[-1] == '\\')
1902                     goto normal_backslash;
1903                 }
1904               goto normal_char;
1905
1906#ifdef emacs
1907            /* There is no way to specify the before_dot and after_dot
1908               operators.  rms says this is ok.  --karl  */
1909            case '=':
1910              BUF_PUSH (at_dot);
1911              break;
1912
1913            case 's':   
1914              laststart = b;
1915              PATFETCH (c);
1916              BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
1917              break;
1918
1919            case 'S':
1920              laststart = b;
1921              PATFETCH (c);
1922              BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
1923              break;
1924#endif /* emacs */
1925
1926
1927            case 'w':
1928              laststart = b;
1929              BUF_PUSH (wordchar);
1930              break;
1931
1932
1933            case 'W':
1934              laststart = b;
1935              BUF_PUSH (notwordchar);
1936              break;
1937
1938
1939            case '<':
1940              BUF_PUSH (wordbeg);
1941              break;
1942
1943            case '>':
1944              BUF_PUSH (wordend);
1945              break;
1946
1947            case 'b':
1948              BUF_PUSH (wordbound);
1949              break;
1950
1951            case 'B':
1952              BUF_PUSH (notwordbound);
1953              break;
1954
1955            case '`':
1956              BUF_PUSH (begbuf);
1957              break;
1958
1959            case '\'':
1960              BUF_PUSH (endbuf);
1961              break;
1962
1963            case '1': case '2': case '3': case '4': case '5':
1964            case '6': case '7': case '8': case '9':
1965              if (syntax & RE_NO_BK_REFS)
1966                goto normal_char;
1967
1968              c1 = c - '0';
1969
1970              if (c1 > regnum)
1971                return REG_ESUBREG;
1972
1973              /* Can't back reference to a subexpression if inside of it.  */
1974              if (group_in_compile_stack (compile_stack, c1))
1975                goto normal_char;
1976
1977              laststart = b;
1978              BUF_PUSH_2 (duplicate, c1);
1979              break;
1980
1981
1982            case '+':
1983            case '?':
1984              if (syntax & RE_BK_PLUS_QM)
1985                goto handle_plus;
1986              else
1987                goto normal_backslash;
1988
1989            default:
1990            normal_backslash:
1991              /* You might think it would be useful for \ to mean
1992                 not to translate; but if we don't translate it
1993                 it will never match anything.  */
1994              c = TRANSLATE (c);
1995              goto normal_char;
1996            }
1997          break;
1998
1999
2000        default:
2001        /* Expects the character in `c'.  */
2002        normal_char:
2003              /* If no exactn currently being built.  */
2004          if (!pending_exact 
2005
2006              /* If last exactn not at current position.  */
2007              || pending_exact + *pending_exact + 1 != b
2008             
2009              /* We have only one byte following the exactn for the count.  */
2010              || *pending_exact == (1 << BYTEWIDTH) - 1
2011
2012              /* If followed by a repetition operator.  */
2013              || *p == '*' || *p == '^'
2014              || ((syntax & RE_BK_PLUS_QM)
2015                  ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2016                  : (*p == '+' || *p == '?'))
2017              || ((syntax & RE_INTERVALS)
2018                  && ((syntax & RE_NO_BK_BRACES)
2019                      ? *p == '{'
2020                      : (p[0] == '\\' && p[1] == '{'))))
2021            {
2022              /* Start building a new exactn.  */
2023             
2024              laststart = b;
2025
2026              BUF_PUSH_2 (exactn, 0);
2027              pending_exact = b - 1;
2028            }
2029           
2030          BUF_PUSH (c);
2031          (*pending_exact)++;
2032          break;
2033        } /* switch (c) */
2034    } /* while p != pend */
2035
2036 
2037  /* Through the pattern now.  */
2038 
2039  if (fixup_alt_jump)
2040    STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2041
2042  if (!COMPILE_STACK_EMPTY) 
2043    return REG_EPAREN;
2044
2045  free (compile_stack.stack);
2046
2047  /* We have succeeded; set the length of the buffer.  */
2048  bufp->used = b - bufp->buffer;
2049
2050#ifdef DEBUG
2051  if (debug)
2052    {
2053      DEBUG_PRINT1 ("\nCompiled pattern: ");
2054      print_compiled_pattern (bufp);
2055    }
2056#endif /* DEBUG */
2057
2058  return REG_NOERROR;
2059} /* regex_compile */
2060
2061/* Subroutines for `regex_compile'.  */
2062
2063/* Store OP at LOC followed by two-byte integer parameter ARG.  */
2064
2065static void
2066store_op1 (op, loc, arg)
2067    re_opcode_t op;
2068    unsigned char *loc;
2069    int arg;
2070{
2071  *loc = (unsigned char) op;
2072  STORE_NUMBER (loc + 1, arg);
2073}
2074
2075
2076/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
2077
2078static void
2079store_op2 (op, loc, arg1, arg2)
2080    re_opcode_t op;
2081    unsigned char *loc;
2082    int arg1, arg2;
2083{
2084  *loc = (unsigned char) op;
2085  STORE_NUMBER (loc + 1, arg1);
2086  STORE_NUMBER (loc + 3, arg2);
2087}
2088
2089
2090/* Copy the bytes from LOC to END to open up three bytes of space at LOC
2091   for OP followed by two-byte integer parameter ARG.  */
2092
2093static void
2094insert_op1 (op, loc, arg, end)
2095    re_opcode_t op;
2096    unsigned char *loc;
2097    int arg;
2098    unsigned char *end;   
2099{
2100  register unsigned char *pfrom = end;
2101  register unsigned char *pto = end + 3;
2102
2103  while (pfrom != loc)
2104    *--pto = *--pfrom;
2105   
2106  store_op1 (op, loc, arg);
2107}
2108
2109
2110/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
2111
2112static void
2113insert_op2 (op, loc, arg1, arg2, end)
2114    re_opcode_t op;
2115    unsigned char *loc;
2116    int arg1, arg2;
2117    unsigned char *end;   
2118{
2119  register unsigned char *pfrom = end;
2120  register unsigned char *pto = end + 5;
2121
2122  while (pfrom != loc)
2123    *--pto = *--pfrom;
2124   
2125  store_op2 (op, loc, arg1, arg2);
2126}
2127
2128
2129/* P points to just after a ^ in PATTERN.  Return true if that ^ comes
2130   after an alternative or a begin-subexpression.  We assume there is at
2131   least one character before the ^.  */
2132
2133static boolean
2134at_begline_loc_p (pattern, p, syntax)
2135    const char *pattern, *p;
2136    reg_syntax_t syntax;
2137{
2138  const char *prev = p - 2;
2139  boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2140 
2141  return
2142       /* After a subexpression?  */
2143       (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2144       /* After an alternative?  */
2145    || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2146}
2147
2148
2149/* The dual of at_begline_loc_p.  This one is for $.  We assume there is
2150   at least one character after the $, i.e., `P < PEND'.  */
2151
2152static boolean
2153at_endline_loc_p (p, pend, syntax)
2154    const char *p, *pend;
2155    int syntax;
2156{
2157  const char *next = p;
2158  boolean next_backslash = *next == '\\';
2159  const char *next_next = p + 1 < pend ? p + 1 : NULL;
2160 
2161  return
2162       /* Before a subexpression?  */
2163       (syntax & RE_NO_BK_PARENS ? *next == ')'
2164        : next_backslash && next_next && *next_next == ')')
2165       /* Before an alternative?  */
2166    || (syntax & RE_NO_BK_VBAR ? *next == '|'
2167        : next_backslash && next_next && *next_next == '|');
2168}
2169
2170
2171/* Returns true if REGNUM is in one of COMPILE_STACK's elements and
2172   false if it's not.  */
2173
2174static boolean
2175group_in_compile_stack (compile_stack, regnum)
2176    compile_stack_type compile_stack;
2177    regnum_t regnum;
2178{
2179  int this_element;
2180
2181  for (this_element = compile_stack.avail - 1; 
2182       this_element >= 0; 
2183       this_element--)
2184    if (compile_stack.stack[this_element].regnum == regnum)
2185      return true;
2186
2187  return false;
2188}
2189
2190
2191/* Read the ending character of a range (in a bracket expression) from the
2192   uncompiled pattern *P_PTR (which ends at PEND).  We assume the
2193   starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
2194   Then we set the translation of all bits between the starting and
2195   ending characters (inclusive) in the compiled pattern B.
2196   
2197   Return an error code.
2198   
2199   We use these short variable names so we can use the same macros as
2200   `regex_compile' itself.  */
2201
2202static reg_errcode_t
2203compile_range (p_ptr, pend, translate, syntax, b)
2204    const char **p_ptr, *pend;
2205    char *translate;
2206    reg_syntax_t syntax;
2207    unsigned char *b;
2208{
2209  unsigned this_char;
2210
2211  const char *p = *p_ptr;
2212  int range_start, range_end;
2213 
2214  if (p == pend)
2215    return REG_ERANGE;
2216
2217  /* Even though the pattern is a signed `char *', we need to fetch
2218     with unsigned char *'s; if the high bit of the pattern character
2219     is set, the range endpoints will be negative if we fetch using a
2220     signed char *.
2221
2222     We also want to fetch the endpoints without translating them; the
2223     appropriate translation is done in the bit-setting loop below.  */
2224  range_start = ((unsigned char *) p)[-2];
2225  range_end   = ((unsigned char *) p)[0];
2226
2227  /* Have to increment the pointer into the pattern string, so the
2228     caller isn't still at the ending character.  */
2229  (*p_ptr)++;
2230
2231  /* If the start is after the end, the range is empty.  */
2232  if (range_start > range_end)
2233    return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2234
2235  /* Here we see why `this_char' has to be larger than an `unsigned
2236     char' -- the range is inclusive, so if `range_end' == 0xff
2237     (assuming 8-bit characters), we would otherwise go into an infinite
2238     loop, since all characters <= 0xff.  */
2239  for (this_char = range_start; this_char <= range_end; this_char++)
2240    {
2241      SET_LIST_BIT (TRANSLATE (this_char));
2242    }
2243 
2244  return REG_NOERROR;
2245}
2246
2247/* Failure stack declarations and macros; both re_compile_fastmap and
2248   re_match_2 use a failure stack.  These have to be macros because of
2249   REGEX_ALLOCATE.  */
2250   
2251
2252/* Number of failure points for which to initially allocate space
2253   when matching.  If this number is exceeded, we allocate more
2254   space, so it is not a hard limit.  */
2255#ifndef INIT_FAILURE_ALLOC
2256#define INIT_FAILURE_ALLOC 5
2257#endif
2258
2259/* Roughly the maximum number of failure points on the stack.  Would be
2260   exactly that if always used MAX_FAILURE_SPACE each time we failed.
2261   This is a variable only so users of regex can assign to it; we never
2262   change it ourselves.  */
2263int re_max_failures = 2000;
2264
2265typedef const unsigned char *fail_stack_elt_t;
2266
2267typedef struct
2268{
2269  fail_stack_elt_t *stack;
2270  unsigned size;
2271  unsigned avail;                       /* Offset of next open position.  */
2272} fail_stack_type;
2273
2274#define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
2275#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2276#define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
2277#define FAIL_STACK_TOP()       (fail_stack.stack[fail_stack.avail])
2278
2279
2280/* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
2281
2282#define INIT_FAIL_STACK()                                               \
2283  do {                                                                  \
2284    fail_stack.stack = (fail_stack_elt_t *)                             \
2285      REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));  \
2286                                                                        \
2287    if (fail_stack.stack == NULL)                                       \
2288      return -2;                                                        \
2289                                                                        \
2290    fail_stack.size = INIT_FAILURE_ALLOC;                               \
2291    fail_stack.avail = 0;                                               \
2292  } while (0)
2293
2294
2295/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
2296
2297   Return 1 if succeeds, and 0 if either ran out of memory
2298   allocating space for it or it was already too large. 
2299   
2300   REGEX_REALLOCATE requires `destination' be declared.   */
2301
2302#define DOUBLE_FAIL_STACK(fail_stack)                                   \
2303  ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS              \
2304   ? 0                                                                  \
2305   : ((fail_stack).stack = (fail_stack_elt_t *)                         \
2306        REGEX_REALLOCATE ((fail_stack).stack,                           \
2307          (fail_stack).size * sizeof (fail_stack_elt_t),                \
2308          ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),        \
2309                                                                        \
2310      (fail_stack).stack == NULL                                        \
2311      ? 0                                                               \
2312      : ((fail_stack).size <<= 1,                                       \
2313         1)))
2314
2315
2316/* Push PATTERN_OP on FAIL_STACK.
2317
2318   Return 1 if was able to do so and 0 if ran out of memory allocating
2319   space to do so.  */
2320#define PUSH_PATTERN_OP(pattern_op, fail_stack)                         \
2321  ((FAIL_STACK_FULL ()                                                  \
2322    && !DOUBLE_FAIL_STACK (fail_stack))                                 \
2323    ? 0                                                                 \
2324    : ((fail_stack).stack[(fail_stack).avail++] = pattern_op,           \
2325       1))
2326
2327/* This pushes an item onto the failure stack.  Must be a four-byte
2328   value.  Assumes the variable `fail_stack'.  Probably should only
2329   be called from within `PUSH_FAILURE_POINT'.  */
2330#define PUSH_FAILURE_ITEM(item)                                         \
2331  fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2332
2333/* The complement operation.  Assumes `fail_stack' is nonempty.  */
2334#define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2335
2336/* Used to omit pushing failure point id's when we're not debugging.  */
2337#ifdef DEBUG
2338#define DEBUG_PUSH PUSH_FAILURE_ITEM
2339#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2340#else
2341#define DEBUG_PUSH(item)
2342#define DEBUG_POP(item_addr)
2343#endif
2344
2345
2346/* Push the information about the state we will need
2347   if we ever fail back to it. 
2348   
2349   Requires variables fail_stack, regstart, regend, reg_info, and
2350   num_regs be declared.  DOUBLE_FAIL_STACK requires `destination' be
2351   declared.
2352   
2353   Does `return FAILURE_CODE' if runs out of memory.  */
2354
2355#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)   \
2356  do {                                                                  \
2357    char *destination;                                                  \
2358    /* Must be int, so when we don't save any registers, the arithmetic \
2359       of 0 + -1 isn't done as unsigned.  */                            \
2360    int this_reg;                                                       \
2361                                                                        \
2362    DEBUG_STATEMENT (failure_id++);                                     \
2363    DEBUG_STATEMENT (nfailure_points_pushed++);                         \
2364    DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);           \
2365    DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
2366    DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
2367                                                                        \
2368    DEBUG_PRINT2 ("  slots needed: %d\n", NUM_FAILURE_ITEMS);           \
2369    DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);       \
2370                                                                        \
2371    /* Ensure we have enough space allocated for what we will push.  */ \
2372    while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)                   \
2373      {                                                                 \
2374        if (!DOUBLE_FAIL_STACK (fail_stack))                    \
2375          return failure_code;                                          \
2376                                                                        \
2377        DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",              \
2378                       (fail_stack).size);                              \
2379        DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2380      }                                                                 \
2381                                                                        \
2382    /* Push the info, starting with the registers.  */                  \
2383    DEBUG_PRINT1 ("\n");                                                \
2384                                                                        \
2385    for (this_reg = lowest_active_reg; this_reg <= highest_active_reg;  \
2386         this_reg++)                                                    \
2387      {                                                                 \
2388        DEBUG_PRINT2 ("  Pushing reg: %d\n", this_reg);                 \
2389        DEBUG_STATEMENT (num_regs_pushed++);                            \
2390                                                                        \
2391        DEBUG_PRINT2 ("    start: 0x%x\n", regstart[this_reg]);         \
2392        PUSH_FAILURE_ITEM (regstart[this_reg]);                         \
2393                                                                        \
2394        DEBUG_PRINT2 ("    end: 0x%x\n", regend[this_reg]);             \
2395        PUSH_FAILURE_ITEM (regend[this_reg]);                           \
2396                                                                        \
2397        DEBUG_PRINT2 ("    info: 0x%x\n      ", reg_info[this_reg]);    \
2398        DEBUG_PRINT2 (" match_null=%d",                                 \
2399                      REG_MATCH_NULL_STRING_P (reg_info[this_reg]));    \
2400        DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));    \
2401        DEBUG_PRINT2 (" matched_something=%d",                          \
2402                      MATCHED_SOMETHING (reg_info[this_reg]));          \
2403        DEBUG_PRINT2 (" ever_matched=%d",                               \
2404                      EVER_MATCHED_SOMETHING (reg_info[this_reg]));     \
2405        DEBUG_PRINT1 ("\n");                                            \
2406        PUSH_FAILURE_ITEM (reg_info[this_reg].word);                    \
2407      }                                                                 \
2408                                                                        \
2409    DEBUG_PRINT2 ("  Pushing  low active reg: %d\n", lowest_active_reg);\
2410    PUSH_FAILURE_ITEM (lowest_active_reg);                              \
2411                                                                        \
2412    DEBUG_PRINT2 ("  Pushing high active reg: %d\n", highest_active_reg);\
2413    PUSH_FAILURE_ITEM (highest_active_reg);                             \
2414                                                                        \
2415    DEBUG_PRINT2 ("  Pushing pattern 0x%x: ", pattern_place);           \
2416    DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);           \
2417    PUSH_FAILURE_ITEM (pattern_place);                                  \
2418                                                                        \
2419    DEBUG_PRINT2 ("  Pushing string 0x%x: `", string_place);            \
2420    DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
2421                                 size2);                                \
2422    DEBUG_PRINT1 ("'\n");                                               \
2423    PUSH_FAILURE_ITEM (string_place);                                   \
2424                                                                        \
2425    DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);            \
2426    DEBUG_PUSH (failure_id);                                            \
2427  } while (0)
2428
2429/* This is the number of items that are pushed and popped on the stack
2430   for each register.  */
2431#define NUM_REG_ITEMS  3
2432
2433/* Individual items aside from the registers.  */
2434#ifdef DEBUG
2435#define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
2436#else
2437#define NUM_NONREG_ITEMS 4
2438#endif
2439
2440/* We push at most this many items on the stack.  */
2441#define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2442
2443/* We actually push this many items.  */
2444#define NUM_FAILURE_ITEMS                                               \
2445  ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS         \
2446    + NUM_NONREG_ITEMS)
2447
2448/* How many items can still be added to the stack without overflowing it.  */
2449#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2450
2451
2452/* Pops what PUSH_FAIL_STACK pushes.
2453
2454   We restore into the parameters, all of which should be lvalues:
2455     STR -- the saved data position.
2456     PAT -- the saved pattern position.
2457     LOW_REG, HIGH_REG -- the highest and lowest active registers.
2458     REGSTART, REGEND -- arrays of string positions.
2459     REG_INFO -- array of information about each subexpression.
2460   
2461   Also assumes the variables `fail_stack' and (if debugging), `bufp',
2462   `pend', `string1', `size1', `string2', and `size2'.  */
2463
2464#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2465{                                                                       \
2466  DEBUG_STATEMENT (fail_stack_elt_t failure_id;)                        \
2467  int this_reg;                                                         \
2468  const unsigned char *string_temp;                                     \
2469                                                                        \
2470  assert (!FAIL_STACK_EMPTY ());                                        \
2471                                                                        \
2472  /* Remove failure points and point to how many regs pushed.  */       \
2473  DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");                                \
2474  DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);    \
2475  DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);     \
2476                                                                        \
2477  assert (fail_stack.avail >= NUM_NONREG_ITEMS);                        \
2478                                                                        \
2479  DEBUG_POP (&failure_id);                                              \
2480  DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);              \
2481                                                                        \
2482  /* If the saved string location is NULL, it came from an              \
2483     on_failure_keep_string_jump opcode, and we want to throw away the  \
2484     saved NULL, thus retaining our current position in the string.  */ \
2485  string_temp = POP_FAILURE_ITEM ();                                    \
2486  if (string_temp != NULL)                                              \
2487    str = (const char *) string_temp;                                   \
2488                                                                        \
2489  DEBUG_PRINT2 ("  Popping string 0x%x: `", str);                       \
2490  DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);      \
2491  DEBUG_PRINT1 ("'\n");                                                 \
2492                                                                        \
2493  pat = (unsigned char *) POP_FAILURE_ITEM ();                          \
2494  DEBUG_PRINT2 ("  Popping pattern 0x%x: ", pat);                       \
2495  DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);                       \
2496                                                                        \
2497  /* Restore register info.  */                                         \
2498  high_reg = (unsigned) POP_FAILURE_ITEM ();                            \
2499  DEBUG_PRINT2 ("  Popping high active reg: %d\n", high_reg);           \
2500                                                                        \
2501  low_reg = (unsigned) POP_FAILURE_ITEM ();                             \
2502  DEBUG_PRINT2 ("  Popping  low active reg: %d\n", low_reg);            \
2503                                                                        \
2504  for (this_reg = high_reg; this_reg >= low_reg; this_reg--)            \
2505    {                                                                   \
2506      DEBUG_PRINT2 ("    Popping reg: %d\n", this_reg);                 \
2507                                                                        \
2508      reg_info[this_reg].word = POP_FAILURE_ITEM ();                    \
2509      DEBUG_PRINT2 ("      info: 0x%x\n", reg_info[this_reg]);          \
2510                                                                        \
2511      regend[this_reg] = (const char *) POP_FAILURE_ITEM ();            \
2512      DEBUG_PRINT2 ("      end: 0x%x\n", regend[this_reg]);             \
2513                                                                        \
2514      regstart[this_reg] = (const char *) POP_FAILURE_ITEM ();          \
2515      DEBUG_PRINT2 ("      start: 0x%x\n", regstart[this_reg]);         \
2516    }                                                                   \
2517                                                                        \
2518  DEBUG_STATEMENT (nfailure_points_popped++);                           \
2519} /* POP_FAILURE_POINT */
2520
2521/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2522   BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
2523   characters can start a string that matches the pattern.  This fastmap
2524   is used by re_search to skip quickly over impossible starting points.
2525
2526   The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2527   area as BUFP->fastmap.
2528   
2529   We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2530   the pattern buffer.
2531
2532   Returns 0 if we succeed, -2 if an internal error.   */
2533
2534int
2535re_compile_fastmap (bufp)
2536     struct re_pattern_buffer *bufp;
2537{
2538  int j, k;
2539  fail_stack_type fail_stack;
2540#ifndef REGEX_MALLOC
2541  char *destination;
2542#endif
2543  /* We don't push any register information onto the failure stack.  */
2544  unsigned num_regs = 0;
2545 
2546  register char *fastmap = bufp->fastmap;
2547  unsigned char *pattern = bufp->buffer;
2548  unsigned long size = bufp->used;
2549  const unsigned char *p = pattern;
2550  register unsigned char *pend = pattern + size;
2551
2552  /* Assume that each path through the pattern can be null until
2553     proven otherwise.  We set this false at the bottom of switch
2554     statement, to which we get only if a particular path doesn't
2555     match the empty string.  */
2556  boolean path_can_be_null = true;
2557
2558  /* We aren't doing a `succeed_n' to begin with.  */
2559  boolean succeed_n_p = false;
2560
2561  assert (fastmap != NULL && p != NULL);
2562 
2563  INIT_FAIL_STACK ();
2564  bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
2565  bufp->fastmap_accurate = 1;       /* It will be when we're done.  */
2566  bufp->can_be_null = 0;
2567     
2568  while (p != pend || !FAIL_STACK_EMPTY ())
2569    {
2570      if (p == pend)
2571        {
2572          bufp->can_be_null |= path_can_be_null;
2573         
2574          /* Reset for next path.  */
2575          path_can_be_null = true;
2576         
2577          p = fail_stack.stack[--fail_stack.avail];
2578        }
2579
2580      /* We should never be about to go beyond the end of the pattern.  */
2581      assert (p < pend);
2582     
2583#ifdef SWITCH_ENUM_BUG
2584      switch ((int) ((re_opcode_t) *p++))
2585#else
2586      switch ((re_opcode_t) *p++)
2587#endif
2588        {
2589
2590        /* I guess the idea here is to simply not bother with a fastmap
2591           if a backreference is used, since it's too hard to figure out
2592           the fastmap for the corresponding group.  Setting
2593           `can_be_null' stops `re_search_2' from using the fastmap, so
2594           that is all we do.  */
2595        case duplicate:
2596          bufp->can_be_null = 1;
2597          return 0;
2598
2599
2600      /* Following are the cases which match a character.  These end
2601         with `break'.  */
2602
2603        case exactn:
2604          fastmap[p[1]] = 1;
2605          break;
2606
2607
2608        case charset:
2609          for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2610            if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2611              fastmap[j] = 1;
2612          break;
2613
2614
2615        case charset_not:
2616          /* Chars beyond end of map must be allowed.  */
2617          for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2618            fastmap[j] = 1;
2619
2620          for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2621            if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2622              fastmap[j] = 1;
2623          break;
2624
2625
2626        case wordchar:
2627          for (j = 0; j < (1 << BYTEWIDTH); j++)
2628            if (SYNTAX (j) == Sword)
2629              fastmap[j] = 1;
2630          break;
2631
2632
2633        case notwordchar:
2634          for (j = 0; j < (1 << BYTEWIDTH); j++)
2635            if (SYNTAX (j) != Sword)
2636              fastmap[j] = 1;
2637          break;
2638
2639
2640        case anychar:
2641          /* `.' matches anything ...  */
2642          for (j = 0; j < (1 << BYTEWIDTH); j++)
2643            fastmap[j] = 1;
2644
2645          /* ... except perhaps newline.  */
2646          if (!(bufp->syntax & RE_DOT_NEWLINE))
2647            fastmap['\n'] = 0;
2648
2649          /* Return if we have already set `can_be_null'; if we have,
2650             then the fastmap is irrelevant.  Something's wrong here.  */
2651          else if (bufp->can_be_null)
2652            return 0;
2653
2654          /* Otherwise, have to check alternative paths.  */
2655          break;
2656
2657
2658#ifdef emacs
2659        case syntaxspec:
2660          k = *p++;
2661          for (j = 0; j < (1 << BYTEWIDTH); j++)
2662            if (SYNTAX (j) == (enum syntaxcode) k)
2663              fastmap[j] = 1;
2664          break;
2665
2666
2667        case notsyntaxspec:
2668          k = *p++;
2669          for (j = 0; j < (1 << BYTEWIDTH); j++)
2670            if (SYNTAX (j) != (enum syntaxcode) k)
2671              fastmap[j] = 1;
2672          break;
2673
2674
2675      /* All cases after this match the empty string.  These end with
2676         `continue'.  */
2677
2678
2679        case before_dot:
2680        case at_dot:
2681        case after_dot:
2682          continue;
2683#endif /* not emacs */
2684
2685
2686        case no_op:
2687        case begline:
2688        case endline:
2689        case begbuf:
2690        case endbuf:
2691        case wordbound:
2692        case notwordbound:
2693        case wordbeg:
2694        case wordend:
2695        case push_dummy_failure:
2696          continue;
2697
2698
2699        case jump_n:
2700        case pop_failure_jump:
2701        case maybe_pop_jump:
2702        case jump:
2703        case jump_past_alt:
2704        case dummy_failure_jump:
2705          EXTRACT_NUMBER_AND_INCR (j, p);
2706          p += j;       
2707          if (j > 0)
2708            continue;
2709           
2710          /* Jump backward implies we just went through the body of a
2711             loop and matched nothing.  Opcode jumped to should be
2712             `on_failure_jump' or `succeed_n'.  Just treat it like an
2713             ordinary jump.  For a * loop, it has pushed its failure
2714             point already; if so, discard that as redundant.  */
2715          if ((re_opcode_t) *p != on_failure_jump
2716              && (re_opcode_t) *p != succeed_n)
2717            continue;
2718
2719          p++;
2720          EXTRACT_NUMBER_AND_INCR (j, p);
2721          p += j;               
2722         
2723          /* If what's on the stack is where we are now, pop it.  */
2724          if (!FAIL_STACK_EMPTY () 
2725              && fail_stack.stack[fail_stack.avail - 1] == p)
2726            fail_stack.avail--;
2727
2728          continue;
2729
2730
2731        case on_failure_jump:
2732        case on_failure_keep_string_jump:
2733        handle_on_failure_jump:
2734          EXTRACT_NUMBER_AND_INCR (j, p);
2735
2736          /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2737             end of the pattern.  We don't want to push such a point,
2738             since when we restore it above, entering the switch will
2739             increment `p' past the end of the pattern.  We don't need
2740             to push such a point since we obviously won't find any more
2741             fastmap entries beyond `pend'.  Such a pattern can match
2742             the null string, though.  */
2743          if (p + j < pend)
2744            {
2745              if (!PUSH_PATTERN_OP (p + j, fail_stack))
2746                return -2;
2747            }
2748          else
2749            bufp->can_be_null = 1;
2750
2751          if (succeed_n_p)
2752            {
2753              EXTRACT_NUMBER_AND_INCR (k, p);   /* Skip the n.  */
2754              succeed_n_p = false;
2755            }
2756
2757          continue;
2758
2759
2760        case succeed_n:
2761          /* Get to the number of times to succeed.  */
2762          p += 2;               
2763
2764          /* Increment p past the n for when k != 0.  */
2765          EXTRACT_NUMBER_AND_INCR (k, p);
2766          if (k == 0)
2767            {
2768              p -= 4;
2769              succeed_n_p = true;  /* Spaghetti code alert.  */
2770              goto handle_on_failure_jump;
2771            }
2772          continue;
2773
2774
2775        case set_number_at:
2776          p += 4;
2777          continue;
2778
2779
2780        case start_memory:
2781        case stop_memory:
2782          p += 2;
2783          continue;
2784
2785
2786        default:
2787          abort (); /* We have listed all the cases.  */
2788        } /* switch *p++ */
2789
2790      /* Getting here means we have found the possible starting
2791         characters for one path of the pattern -- and that the empty
2792         string does not match.  We need not follow this path further.
2793         Instead, look at the next alternative (remembered on the
2794         stack), or quit if no more.  The test at the top of the loop
2795         does these things.  */
2796      path_can_be_null = false;
2797      p = pend;
2798    } /* while p */
2799
2800  /* Set `can_be_null' for the last path (also the first path, if the
2801     pattern is empty).  */
2802  bufp->can_be_null |= path_can_be_null;
2803  return 0;
2804} /* re_compile_fastmap */
2805
2806/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
2807   ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
2808   this memory for recording register information.  STARTS and ENDS
2809   must be allocated using the malloc library routine, and must each
2810   be at least NUM_REGS * sizeof (regoff_t) bytes long.
2811
2812   If NUM_REGS == 0, then subsequent matches should allocate their own
2813   register data.
2814
2815   Unless this function is called, the first search or match using
2816   PATTERN_BUFFER will allocate its own register data, without
2817   freeing the old data.  */
2818
2819void
2820re_set_registers (bufp, regs, num_regs, starts, ends)
2821    struct re_pattern_buffer *bufp;
2822    struct re_registers *regs;
2823    unsigned num_regs;
2824    regoff_t *starts, *ends;
2825{
2826  if (num_regs)
2827    {
2828      bufp->regs_allocated = REGS_REALLOCATE;
2829      regs->num_regs = num_regs;
2830      regs->start = starts;
2831      regs->end = ends;
2832    }
2833  else
2834    {
2835      bufp->regs_allocated = REGS_UNALLOCATED;
2836      regs->num_regs = 0;
2837      regs->start = regs->end = (regoff_t) 0;
2838    }
2839}
2840
2841/* Searching routines.  */
2842
2843/* Like re_search_2, below, but only one string is specified, and
2844   doesn't let you say where to stop matching. */
2845
2846int
2847re_search (bufp, string, size, startpos, range, regs)
2848     struct re_pattern_buffer *bufp;
2849     const char *string;
2850     int size, startpos, range;
2851     struct re_registers *regs;
2852{
2853  return re_search_2 (bufp, NULL, 0, string, size, startpos, range, 
2854                      regs, size);
2855}
2856
2857
2858/* Using the compiled pattern in BUFP->buffer, first tries to match the
2859   virtual concatenation of STRING1 and STRING2, starting first at index
2860   STARTPOS, then at STARTPOS + 1, and so on.
2861   
2862   STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2863   
2864   RANGE is how far to scan while trying to match.  RANGE = 0 means try
2865   only at STARTPOS; in general, the last start tried is STARTPOS +
2866   RANGE.
2867   
2868   In REGS, return the indices of the virtual concatenation of STRING1
2869   and STRING2 that matched the entire BUFP->buffer and its contained
2870   subexpressions.
2871   
2872   Do not consider matching one past the index STOP in the virtual
2873   concatenation of STRING1 and STRING2.
2874
2875   We return either the position in the strings at which the match was
2876   found, -1 if no match, or -2 if error (such as failure
2877   stack overflow).  */
2878
2879int
2880re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
2881     struct re_pattern_buffer *bufp;
2882     const char *string1, *string2;
2883     int size1, size2;
2884     int startpos;
2885     int range;
2886     struct re_registers *regs;
2887     int stop;
2888{
2889  int val;
2890  register char *fastmap = bufp->fastmap;
2891  register char *translate = bufp->translate;
2892  int total_size = size1 + size2;
2893  int endpos = startpos + range;
2894
2895  /* Check for out-of-range STARTPOS.  */
2896  if (startpos < 0 || startpos > total_size)
2897    return -1;
2898   
2899  /* Fix up RANGE if it might eventually take us outside
2900     the virtual concatenation of STRING1 and STRING2.  */
2901  if (endpos < -1)
2902    range = -1 - startpos;
2903  else if (endpos > total_size)
2904    range = total_size - startpos;
2905
2906  /* If the search isn't to be a backwards one, don't waste time in a
2907     search for a pattern that must be anchored.  */
2908  if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
2909    {
2910      if (startpos > 0)
2911        return -1;
2912      else
2913        range = 1;
2914    }
2915
2916  /* Update the fastmap now if not correct already.  */
2917  if (fastmap && !bufp->fastmap_accurate)
2918    if (re_compile_fastmap (bufp) == -2)
2919      return -2;
2920 
2921  /* Loop through the string, looking for a place to start matching.  */
2922  for (;;)
2923    { 
2924      /* If a fastmap is supplied, skip quickly over characters that
2925         cannot be the start of a match.  If the pattern can match the
2926         null string, however, we don't need to skip characters; we want
2927         the first null string.  */
2928      if (fastmap && startpos < total_size && !bufp->can_be_null)
2929        {
2930          if (range > 0)        /* Searching forwards.  */
2931            {
2932              register const char *d;
2933              register int lim = 0;
2934              int irange = range;
2935
2936              if (startpos < size1 && startpos + range >= size1)
2937                lim = range - (size1 - startpos);
2938
2939              d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2940   
2941              /* Written out as an if-else to avoid testing `translate'
2942                 inside the loop.  */
2943              if (translate)
2944                while (range > lim
2945                       && !fastmap[(unsigned char)
2946                                   translate[(unsigned char) *d++]])
2947                  range--;
2948              else
2949                while (range > lim && !fastmap[(unsigned char) *d++])
2950                  range--;
2951
2952              startpos += irange - range;
2953            }
2954          else                          /* Searching backwards.  */
2955            {
2956              register char c = (size1 == 0 || startpos >= size1
2957                                 ? string2[startpos - size1] 
2958                                 : string1[startpos]);
2959
2960              if (!fastmap[(unsigned char) TRANSLATE (c)])
2961                goto advance;
2962            }
2963        }
2964
2965      /* If can't match the null string, and that's all we have left, fail.  */
2966      if (range >= 0 && startpos == total_size && fastmap
2967          && !bufp->can_be_null)
2968        return -1;
2969
2970      val = re_match_2 (bufp, string1, size1, string2, size2,
2971                        startpos, regs, stop);
2972      if (val >= 0)
2973        return startpos;
2974       
2975      if (val == -2)
2976        return -2;
2977
2978    advance:
2979      if (!range) 
2980        break;
2981      else if (range > 0) 
2982        {
2983          range--; 
2984          startpos++;
2985        }
2986      else
2987        {
2988          range++; 
2989          startpos--;
2990        }
2991    }
2992  return -1;
2993} /* re_search_2 */
2994
2995/* Declarations and macros for re_match_2.  */
2996
2997static int bcmp_translate ();
2998static boolean alt_match_null_string_p (),
2999               common_op_match_null_string_p (),
3000               group_match_null_string_p ();
3001
3002/* Structure for per-register (a.k.a. per-group) information.
3003   This must not be longer than one word, because we push this value
3004   onto the failure stack.  Other register information, such as the
3005   starting and ending positions (which are addresses), and the list of
3006   inner groups (which is a bits list) are maintained in separate
3007   variables. 
3008   
3009   We are making a (strictly speaking) nonportable assumption here: that
3010   the compiler will pack our bit fields into something that fits into
3011   the type of `word', i.e., is something that fits into one item on the
3012   failure stack.  */
3013typedef union
3014{
3015  fail_stack_elt_t word;
3016  struct
3017  {
3018      /* This field is one if this group can match the empty string,
3019         zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
3020#define MATCH_NULL_UNSET_VALUE 3
3021    unsigned match_null_string_p : 2;
3022    unsigned is_active : 1;
3023    unsigned matched_something : 1;
3024    unsigned ever_matched_something : 1;
3025  } bits;
3026} register_info_type;
3027
3028#define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
3029#define IS_ACTIVE(R)  ((R).bits.is_active)
3030#define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
3031#define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
3032
3033
3034/* Call this when have matched a real character; it sets `matched' flags
3035   for the subexpressions which we are currently inside.  Also records
3036   that those subexprs have matched.  */
3037#define SET_REGS_MATCHED()                                              \
3038  do                                                                    \
3039    {                                                                   \
3040      unsigned r;                                                       \
3041      for (r = lowest_active_reg; r <= highest_active_reg; r++)         \
3042        {                                                               \
3043          MATCHED_SOMETHING (reg_info[r])                               \
3044            = EVER_MATCHED_SOMETHING (reg_info[r])                      \
3045            = 1;                                                        \
3046        }                                                               \
3047    }                                                                   \
3048  while (0)
3049
3050
3051/* This converts PTR, a pointer into one of the search strings `string1'
3052   and `string2' into an offset from the beginning of that string.  */
3053#define POINTER_TO_OFFSET(ptr)                                          \
3054  (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
3055
3056/* Registers are set to a sentinel when they haven't yet matched.  */
3057#define REG_UNSET_VALUE ((char *) -1)
3058#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
3059
3060
3061/* Macros for dealing with the split strings in re_match_2.  */
3062
3063#define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
3064
3065/* Call before fetching a character with *d.  This switches over to
3066   string2 if necessary.  */
3067#define PREFETCH()                                                      \
3068  while (d == dend)                                                     \
3069    {                                                                   \
3070      /* End of string2 => fail.  */                                    \
3071      if (dend == end_match_2)                                          \
3072        goto fail;                                                      \
3073      /* End of string1 => advance to string2.  */                      \
3074      d = string2;                                                      \
3075      dend = end_match_2;                                               \
3076    }
3077
3078
3079/* Test if at very beginning or at very end of the virtual concatenation
3080   of `string1' and `string2'.  If only one string, it's `string2'.  */
3081#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3082#define AT_STRINGS_END(d) ((d) == end2)
3083
3084
3085/* Test if D points to a character which is word-constituent.  We have
3086   two special cases to check for: if past the end of string1, look at
3087   the first character in string2; and if before the beginning of
3088   string2, look at the last character in string1.  */
3089#define WORDCHAR_P(d)                                                   \
3090  (SYNTAX ((d) == end1 ? *string2                                       \
3091           : (d) == string2 - 1 ? *(end1 - 1) : *(d))                   \
3092   == Sword)
3093
3094/* Test if the character before D and the one at D differ with respect
3095   to being word-constituent.  */
3096#define AT_WORD_BOUNDARY(d)                                             \
3097  (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                             \
3098   || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3099
3100
3101/* Free everything we malloc.  */
3102#ifdef REGEX_MALLOC
3103#define FREE_VAR(var) if (var) free (var); var = NULL
3104#define FREE_VARIABLES()                                                \
3105  do {                                                                  \
3106    FREE_VAR (fail_stack.stack);                                        \
3107    FREE_VAR (regstart);                                                \
3108    FREE_VAR (regend);                                                  \
3109    FREE_VAR (old_regstart);                                            \
3110    FREE_VAR (old_regend);                                              \
3111    FREE_VAR (best_regstart);                                           \
3112    FREE_VAR (best_regend);                                             \
3113    FREE_VAR (reg_info);                                                \
3114    FREE_VAR (reg_dummy);                                               \
3115    FREE_VAR (reg_info_dummy);                                          \
3116  } while (0)
3117#else /* not REGEX_MALLOC */
3118/* Some MIPS systems (at least) want this to free alloca'd storage.  */
3119#define FREE_VARIABLES() alloca (0)
3120#endif /* not REGEX_MALLOC */
3121
3122
3123/* These values must meet several constraints.  They must not be valid
3124   register values; since we have a limit of 255 registers (because
3125   we use only one byte in the pattern for the register number), we can
3126   use numbers larger than 255.  They must differ by 1, because of
3127   NUM_FAILURE_ITEMS above.  And the value for the lowest register must
3128   be larger than the value for the highest register, so we do not try
3129   to actually save any registers when none are active.  */
3130#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3131#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3132
3133/* Matching routines.  */
3134
3135#ifndef emacs   /* Emacs never uses this.  */
3136/* re_match is like re_match_2 except it takes only a single string.  */
3137
3138int
3139re_match (bufp, string, size, pos, regs)
3140     struct re_pattern_buffer *bufp;
3141     const char *string;
3142     int size, pos;
3143     struct re_registers *regs;
3144 {
3145  return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size); 
3146}
3147#endif /* not emacs */
3148
3149
3150/* re_match_2 matches the compiled pattern in BUFP against the
3151   the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3152   and SIZE2, respectively).  We start matching at POS, and stop
3153   matching at STOP.
3154   
3155   If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3156   store offsets for the substring each group matched in REGS.  See the
3157   documentation for exactly how many groups we fill.
3158
3159   We return -1 if no match, -2 if an internal error (such as the
3160   failure stack overflowing).  Otherwise, we return the length of the
3161   matched substring.  */
3162
3163int
3164re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3165     struct re_pattern_buffer *bufp;
3166     const char *string1, *string2;
3167     int size1, size2;
3168     int pos;
3169     struct re_registers *regs;
3170     int stop;
3171{
3172  /* General temporaries.  */
3173  int mcnt;
3174  unsigned char *p1;
3175
3176  /* Just past the end of the corresponding string.  */
3177  const char *end1, *end2;
3178
3179  /* Pointers into string1 and string2, just past the last characters in
3180     each to consider matching.  */
3181  const char *end_match_1, *end_match_2;
3182
3183  /* Where we are in the data, and the end of the current string.  */
3184  const char *d, *dend;
3185 
3186  /* Where we are in the pattern, and the end of the pattern.  */
3187  unsigned char *p = bufp->buffer;
3188  register unsigned char *pend = p + bufp->used;
3189
3190  /* We use this to map every character in the string.  */
3191  char *translate = bufp->translate;
3192
3193  /* Failure point stack.  Each place that can handle a failure further
3194     down the line pushes a failure point on this stack.  It consists of
3195     restart, regend, and reg_info for all registers corresponding to
3196     the subexpressions we're currently inside, plus the number of such
3197     registers, and, finally, two char *'s.  The first char * is where
3198     to resume scanning the pattern; the second one is where to resume
3199     scanning the strings.  If the latter is zero, the failure point is
3200     a ``dummy''; if a failure happens and the failure point is a dummy,
3201     it gets discarded and the next next one is tried.  */
3202  fail_stack_type fail_stack;
3203#ifdef DEBUG
3204  static unsigned failure_id = 0;
3205  unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3206#endif
3207
3208  /* We fill all the registers internally, independent of what we
3209     return, for use in backreferences.  The number here includes
3210     an element for register zero.  */
3211  unsigned num_regs = bufp->re_nsub + 1;
3212 
3213  /* The currently active registers.  */
3214  unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3215  unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3216
3217  /* Information on the contents of registers. These are pointers into
3218     the input strings; they record just what was matched (on this
3219     attempt) by a subexpression part of the pattern, that is, the
3220     regnum-th regstart pointer points to where in the pattern we began
3221     matching and the regnum-th regend points to right after where we
3222     stopped matching the regnum-th subexpression.  (The zeroth register
3223     keeps track of what the whole pattern matches.)  */
3224  const char **regstart, **regend;
3225
3226  /* If a group that's operated upon by a repetition operator fails to
3227     match anything, then the register for its start will need to be
3228     restored because it will have been set to wherever in the string we
3229     are when we last see its open-group operator.  Similarly for a
3230     register's end.  */
3231  const char **old_regstart, **old_regend;
3232
3233  /* The is_active field of reg_info helps us keep track of which (possibly
3234     nested) subexpressions we are currently in. The matched_something
3235     field of reg_info[reg_num] helps us tell whether or not we have
3236     matched any of the pattern so far this time through the reg_num-th
3237     subexpression.  These two fields get reset each time through any
3238     loop their register is in.  */
3239  register_info_type *reg_info; 
3240
3241  /* The following record the register info as found in the above
3242     variables when we find a match better than any we've seen before.
3243     This happens as we backtrack through the failure points, which in
3244     turn happens only if we have not yet matched the entire string. */
3245  unsigned best_regs_set = false;
3246  const char **best_regstart, **best_regend;
3247 
3248  /* Logically, this is `best_regend[0]'.  But we don't want to have to
3249     allocate space for that if we're not allocating space for anything
3250     else (see below).  Also, we never need info about register 0 for
3251     any of the other register vectors, and it seems rather a kludge to
3252     treat `best_regend' differently than the rest.  So we keep track of
3253     the end of the best match so far in a separate variable.  We
3254     initialize this to NULL so that when we backtrack the first time
3255     and need to test it, it's not garbage.  */
3256  const char *match_end = NULL;
3257
3258  /* Used when we pop values we don't care about.  */
3259  const char **reg_dummy;
3260  register_info_type *reg_info_dummy;
3261
3262#ifdef DEBUG
3263  /* Counts the total number of registers pushed.  */
3264  unsigned num_regs_pushed = 0;         
3265#endif
3266
3267  DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3268 
3269  INIT_FAIL_STACK ();
3270 
3271  /* Do not bother to initialize all the register variables if there are
3272     no groups in the pattern, as it takes a fair amount of time.  If
3273     there are groups, we include space for register 0 (the whole
3274     pattern), even though we never use it, since it simplifies the
3275     array indexing.  We should fix this.  */
3276  if (bufp->re_nsub)
3277    {
3278      regstart = REGEX_TALLOC (num_regs, const char *);
3279      regend = REGEX_TALLOC (num_regs, const char *);
3280      old_regstart = REGEX_TALLOC (num_regs, const char *);
3281      old_regend = REGEX_TALLOC (num_regs, const char *);
3282      best_regstart = REGEX_TALLOC (num_regs, const char *);
3283      best_regend = REGEX_TALLOC (num_regs, const char *);
3284      reg_info = REGEX_TALLOC (num_regs, register_info_type);
3285      reg_dummy = REGEX_TALLOC (num_regs, const char *);
3286      reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3287
3288      if (!(regstart && regend && old_regstart && old_regend && reg_info 
3289            && best_regstart && best_regend && reg_dummy && reg_info_dummy)) 
3290        {
3291          FREE_VARIABLES ();
3292          return -2;
3293        }
3294    }
3295#ifdef REGEX_MALLOC
3296  else
3297    {
3298      /* We must initialize all our variables to NULL, so that
3299         `FREE_VARIABLES' doesn't try to free them.  */
3300      regstart = regend = old_regstart = old_regend = best_regstart
3301        = best_regend = reg_dummy = NULL;
3302      reg_info = reg_info_dummy = (register_info_type *) NULL;
3303    }
3304#endif /* REGEX_MALLOC */
3305
3306  /* The starting position is bogus.  */
3307  if (pos < 0 || pos > size1 + size2)
3308    {
3309      FREE_VARIABLES ();
3310      return -1;
3311    }
3312   
3313  /* Initialize subexpression text positions to -1 to mark ones that no
3314     start_memory/stop_memory has been seen for. Also initialize the
3315     register information struct.  */
3316  for (mcnt = 1; mcnt < num_regs; mcnt++)
3317    {
3318      regstart[mcnt] = regend[mcnt] 
3319        = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3320       
3321      REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3322      IS_ACTIVE (reg_info[mcnt]) = 0;
3323      MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3324      EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3325    }
3326 
3327  /* We move `string1' into `string2' if the latter's empty -- but not if
3328     `string1' is null.  */
3329  if (size2 == 0 && string1 != NULL)
3330    {
3331      string2 = string1;
3332      size2 = size1;
3333      string1 = 0;
3334      size1 = 0;
3335    }
3336  end1 = string1 + size1;
3337  end2 = string2 + size2;
3338
3339  /* Compute where to stop matching, within the two strings.  */
3340  if (stop <= size1)
3341    {
3342      end_match_1 = string1 + stop;
3343      end_match_2 = string2;
3344    }
3345  else
3346    {
3347      end_match_1 = end1;
3348      end_match_2 = string2 + stop - size1;
3349    }
3350
3351  /* `p' scans through the pattern as `d' scans through the data.
3352     `dend' is the end of the input string that `d' points within.  `d'
3353     is advanced into the following input string whenever necessary, but
3354     this happens before fetching; therefore, at the beginning of the
3355     loop, `d' can be pointing at the end of a string, but it cannot
3356     equal `string2'.  */
3357  if (size1 > 0 && pos <= size1)
3358    {
3359      d = string1 + pos;
3360      dend = end_match_1;
3361    }
3362  else
3363    {
3364      d = string2 + pos - size1;
3365      dend = end_match_2;
3366    }
3367
3368  DEBUG_PRINT1 ("The compiled pattern is: ");
3369  DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3370  DEBUG_PRINT1 ("The string to match is: `");
3371  DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3372  DEBUG_PRINT1 ("'\n");
3373 
3374  /* This loops over pattern commands.  It exits by returning from the
3375     function if the match is complete, or it drops through if the match
3376     fails at this starting point in the input data.  */
3377  for (;;)
3378    {
3379      DEBUG_PRINT2 ("\n0x%x: ", p);
3380
3381      if (p == pend)
3382        { /* End of pattern means we might have succeeded.  */
3383          DEBUG_PRINT1 ("end of pattern ... ");
3384         
3385          /* If we haven't matched the entire string, and we want the
3386             longest match, try backtracking.  */
3387          if (d != end_match_2)
3388            {
3389              DEBUG_PRINT1 ("backtracking.\n");
3390             
3391              if (!FAIL_STACK_EMPTY ())
3392                { /* More failure points to try.  */
3393                  boolean same_str_p = (FIRST_STRING_P (match_end) 
3394                                        == MATCHING_IN_FIRST_STRING);
3395
3396                  /* If exceeds best match so far, save it.  */
3397                  if (!best_regs_set
3398                      || (same_str_p && d > match_end)
3399                      || (!same_str_p && !MATCHING_IN_FIRST_STRING))
3400                    {
3401                      best_regs_set = true;
3402                      match_end = d;
3403                     
3404                      DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3405                     
3406                      for (mcnt = 1; mcnt < num_regs; mcnt++)
3407                        {
3408                          best_regstart[mcnt] = regstart[mcnt];
3409                          best_regend[mcnt] = regend[mcnt];
3410                        }
3411                    }
3412                  goto fail;           
3413                }
3414
3415              /* If no failure points, don't restore garbage.  */
3416              else if (best_regs_set)   
3417                {
3418                restore_best_regs:
3419                  /* Restore best match.  It may happen that `dend ==
3420                     end_match_1' while the restored d is in string2.
3421                     For example, the pattern `x.*y.*z' against the
3422                     strings `x-' and `y-z-', if the two strings are
3423                     not consecutive in memory.  */
3424                  DEBUG_PRINT1 ("Restoring best registers.\n");
3425                 
3426                  d = match_end;
3427                  dend = ((d >= string1 && d <= end1)
3428                           ? end_match_1 : end_match_2);
3429
3430                  for (mcnt = 1; mcnt < num_regs; mcnt++)
3431                    {
3432                      regstart[mcnt] = best_regstart[mcnt];
3433                      regend[mcnt] = best_regend[mcnt];
3434                    }
3435                }
3436            } /* d != end_match_2 */
3437
3438          DEBUG_PRINT1 ("Accepting match.\n");
3439
3440          /* If caller wants register contents data back, do it.  */
3441          if (regs && !bufp->no_sub)
3442            {
3443              /* Have the register data arrays been allocated?  */
3444              if (bufp->regs_allocated == REGS_UNALLOCATED)
3445                { /* No.  So allocate them with malloc.  We need one
3446                     extra element beyond `num_regs' for the `-1' marker
3447                     GNU code uses.  */
3448                  regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3449                  regs->start = TALLOC (regs->num_regs, regoff_t);
3450                  regs->end = TALLOC (regs->num_regs, regoff_t);
3451                  if (regs->start == NULL || regs->end == NULL)
3452                    return -2;
3453                  bufp->regs_allocated = REGS_REALLOCATE;
3454                }
3455              else if (bufp->regs_allocated == REGS_REALLOCATE)
3456                { /* Yes.  If we need more elements than were already
3457                     allocated, reallocate them.  If we need fewer, just
3458                     leave it alone.  */
3459                  if (regs->num_regs < num_regs + 1)
3460                    {
3461                      regs->num_regs = num_regs + 1;
3462                      RETALLOC (regs->start, regs->num_regs, regoff_t);
3463                      RETALLOC (regs->end, regs->num_regs, regoff_t);
3464                      if (regs->start == NULL || regs->end == NULL)
3465                        return -2;
3466                    }
3467                }
3468              else
3469                assert (bufp->regs_allocated == REGS_FIXED);
3470
3471              /* Convert the pointer data in `regstart' and `regend' to
3472                 indices.  Register zero has to be set differently,
3473                 since we haven't kept track of any info for it.  */
3474              if (regs->num_regs > 0)
3475                {
3476                  regs->start[0] = pos;
3477                  regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3478                                  : d - string2 + size1);
3479                }
3480             
3481              /* Go through the first `min (num_regs, regs->num_regs)'
3482                 registers, since that is all we initialized.  */
3483              for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3484                {
3485                  if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3486                    regs->start[mcnt] = regs->end[mcnt] = -1;
3487                  else
3488                    {
3489                      regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
3490                      regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
3491                    }
3492                }
3493             
3494              /* If the regs structure we return has more elements than
3495                 were in the pattern, set the extra elements to -1.  If
3496                 we (re)allocated the registers, this is the case,
3497                 because we always allocate enough to have at least one
3498                 -1 at the end.  */
3499              for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3500                regs->start[mcnt] = regs->end[mcnt] = -1;
3501            } /* regs && !bufp->no_sub */
3502
3503          FREE_VARIABLES ();
3504          DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3505                        nfailure_points_pushed, nfailure_points_popped,
3506                        nfailure_points_pushed - nfailure_points_popped);
3507          DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3508
3509          mcnt = d - pos - (MATCHING_IN_FIRST_STRING 
3510                            ? string1 
3511                            : string2 - size1);
3512
3513          DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3514
3515          return mcnt;
3516        }
3517
3518      /* Otherwise match next pattern command.  */
3519#ifdef SWITCH_ENUM_BUG
3520      switch ((int) ((re_opcode_t) *p++))
3521#else
3522      switch ((re_opcode_t) *p++)
3523#endif
3524        {
3525        /* Ignore these.  Used to ignore the n of succeed_n's which
3526           currently have n == 0.  */
3527        case no_op:
3528          DEBUG_PRINT1 ("EXECUTING no_op.\n");
3529          break;
3530
3531
3532        /* Match the next n pattern characters exactly.  The following
3533           byte in the pattern defines n, and the n bytes after that
3534           are the characters to match.  */
3535        case exactn:
3536          mcnt = *p++;
3537          DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3538
3539          /* This is written out as an if-else so we don't waste time
3540             testing `translate' inside the loop.  */
3541          if (translate)
3542            {
3543              do
3544                {
3545                  PREFETCH ();
3546                  if (translate[(unsigned char) *d++] != (char) *p++)
3547                    goto fail;
3548                }
3549              while (--mcnt);
3550            }
3551          else
3552            {
3553              do
3554                {
3555                  PREFETCH ();
3556                  if (*d++ != (char) *p++) goto fail;
3557                }
3558              while (--mcnt);
3559            }
3560          SET_REGS_MATCHED ();
3561          break;
3562
3563
3564        /* Match any character except possibly a newline or a null.  */
3565        case anychar:
3566          DEBUG_PRINT1 ("EXECUTING anychar.\n");
3567
3568          PREFETCH ();
3569
3570          if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3571              || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3572            goto fail;
3573
3574          SET_REGS_MATCHED ();
3575          DEBUG_PRINT2 ("  Matched `%d'.\n", *d);
3576          d++;
3577          break;
3578
3579
3580        case charset:
3581        case charset_not:
3582          {
3583            register unsigned char c;
3584            boolean not = (re_opcode_t) *(p - 1) == charset_not;
3585
3586            DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3587
3588            PREFETCH ();
3589            c = TRANSLATE (*d); /* The character to match.  */
3590
3591            /* Cast to `unsigned' instead of `unsigned char' in case the
3592               bit list is a full 32 bytes long.  */
3593            if (c < (unsigned) (*p * BYTEWIDTH)
3594                && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3595              not = !not;
3596
3597            p += 1 + *p;
3598
3599            if (!not) goto fail;
3600           
3601            SET_REGS_MATCHED ();
3602            d++;
3603            break;
3604          }
3605
3606
3607        /* The beginning of a group is represented by start_memory.
3608           The arguments are the register number in the next byte, and the
3609           number of groups inner to this one in the next.  The text
3610           matched within the group is recorded (in the internal
3611           registers data structure) under the register number.  */
3612        case start_memory:
3613          DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3614
3615          /* Find out if this group can match the empty string.  */
3616          p1 = p;               /* To send to group_match_null_string_p.  */
3617         
3618          if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3619            REG_MATCH_NULL_STRING_P (reg_info[*p]) 
3620              = group_match_null_string_p (&p1, pend, reg_info);
3621
3622          /* Save the position in the string where we were the last time
3623             we were at this open-group operator in case the group is
3624             operated upon by a repetition operator, e.g., with `(a*)*b'
3625             against `ab'; then we want to ignore where we are now in
3626             the string in case this attempt to match fails.  */
3627          old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3628                             ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3629                             : regstart[*p];
3630          DEBUG_PRINT2 ("  old_regstart: %d\n", 
3631                         POINTER_TO_OFFSET (old_regstart[*p]));
3632
3633          regstart[*p] = d;
3634          DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3635
3636          IS_ACTIVE (reg_info[*p]) = 1;
3637          MATCHED_SOMETHING (reg_info[*p]) = 0;
3638         
3639          /* This is the new highest active register.  */
3640          highest_active_reg = *p;
3641         
3642          /* If nothing was active before, this is the new lowest active
3643             register.  */
3644          if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3645            lowest_active_reg = *p;
3646
3647          /* Move past the register number and inner group count.  */
3648          p += 2;
3649          break;
3650
3651
3652        /* The stop_memory opcode represents the end of a group.  Its
3653           arguments are the same as start_memory's: the register
3654           number, and the number of inner groups.  */
3655        case stop_memory:
3656          DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3657             
3658          /* We need to save the string position the last time we were at
3659             this close-group operator in case the group is operated
3660             upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3661             against `aba'; then we want to ignore where we are now in
3662             the string in case this attempt to match fails.  */
3663          old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3664                           ? REG_UNSET (regend[*p]) ? d : regend[*p]
3665                           : regend[*p];
3666          DEBUG_PRINT2 ("      old_regend: %d\n", 
3667                         POINTER_TO_OFFSET (old_regend[*p]));
3668
3669          regend[*p] = d;
3670          DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
3671
3672          /* This register isn't active anymore.  */
3673          IS_ACTIVE (reg_info[*p]) = 0;
3674         
3675          /* If this was the only register active, nothing is active
3676             anymore.  */
3677          if (lowest_active_reg == highest_active_reg)
3678            {
3679              lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3680              highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3681            }
3682          else
3683            { /* We must scan for the new highest active register, since
3684                 it isn't necessarily one less than now: consider
3685                 (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
3686                 new highest active register is 1.  */
3687              unsigned char r = *p - 1;
3688              while (r > 0 && !IS_ACTIVE (reg_info[r]))
3689                r--;
3690             
3691              /* If we end up at register zero, that means that we saved
3692                 the registers as the result of an `on_failure_jump', not
3693                 a `start_memory', and we jumped to past the innermost
3694                 `stop_memory'.  For example, in ((.)*) we save
3695                 registers 1 and 2 as a result of the *, but when we pop
3696                 back to the second ), we are at the stop_memory 1.
3697                 Thus, nothing is active.  */
3698              if (r == 0)
3699                {
3700                  lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3701                  highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3702                }
3703              else
3704                highest_active_reg = r;
3705            }
3706         
3707          /* If just failed to match something this time around with a
3708             group that's operated on by a repetition operator, try to
3709             force exit from the ``loop'', and restore the register
3710             information for this group that we had before trying this
3711             last match.  */
3712          if ((!MATCHED_SOMETHING (reg_info[*p])
3713               || (re_opcode_t) p[-3] == start_memory)
3714              && (p + 2) < pend)             
3715            {
3716              boolean is_a_jump_n = false;
3717             
3718              p1 = p + 2;
3719              mcnt = 0;
3720              switch ((re_opcode_t) *p1++)
3721                {
3722                  case jump_n:
3723                    is_a_jump_n = true;
3724                  case pop_failure_jump:
3725                  case maybe_pop_jump:
3726                  case jump:
3727                  case dummy_failure_jump:
3728                    EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3729                    if (is_a_jump_n)
3730                      p1 += 2;
3731                    break;
3732                 
3733                  default:
3734                    /* do nothing */ ;
3735                }
3736              p1 += mcnt;
3737       
3738              /* If the next operation is a jump backwards in the pattern
3739                 to an on_failure_jump right before the start_memory
3740                 corresponding to this stop_memory, exit from the loop
3741                 by forcing a failure after pushing on the stack the
3742                 on_failure_jump's jump in the pattern, and d.  */
3743              if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
3744                  && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
3745                {
3746                  /* If this group ever matched anything, then restore
3747                     what its registers were before trying this last
3748                     failed match, e.g., with `(a*)*b' against `ab' for
3749                     regstart[1], and, e.g., with `((a*)*(b*)*)*'
3750                     against `aba' for regend[3].
3751                     
3752                     Also restore the registers for inner groups for,
3753                     e.g., `((a*)(b*))*' against `aba' (register 3 would
3754                     otherwise get trashed).  */
3755                     
3756                  if (EVER_MATCHED_SOMETHING (reg_info[*p]))
3757                    {
3758                      unsigned r; 
3759       
3760                      EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
3761                     
3762                      /* Restore this and inner groups' (if any) registers.  */
3763                      for (r = *p; r < *p + *(p + 1); r++)
3764                        {
3765                          regstart[r] = old_regstart[r];
3766
3767                          /* xx why this test?  */
3768                          if ((int) old_regend[r] >= (int) regstart[r])
3769                            regend[r] = old_regend[r];
3770                        }     
3771                    }
3772                  p1++;
3773                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
3774                  PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
3775
3776                  goto fail;
3777                }
3778            }
3779         
3780          /* Move past the register number and the inner group count.  */
3781          p += 2;
3782          break;
3783
3784
3785        /* \<digit> has been turned into a `duplicate' command which is
3786           followed by the numeric value of <digit> as the register number.  */
3787        case duplicate:
3788          {
3789            register const char *d2, *dend2;
3790            int regno = *p++;   /* Get which register to match against.  */
3791            DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
3792
3793            /* Can't back reference a group which we've never matched.  */
3794            if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
3795              goto fail;
3796             
3797            /* Where in input to try to start matching.  */
3798            d2 = regstart[regno];
3799           
3800            /* Where to stop matching; if both the place to start and
3801               the place to stop matching are in the same string, then
3802               set to the place to stop, otherwise, for now have to use
3803               the end of the first string.  */
3804
3805            dend2 = ((FIRST_STRING_P (regstart[regno]) 
3806                      == FIRST_STRING_P (regend[regno]))
3807                     ? regend[regno] : end_match_1);
3808            for (;;)
3809              {
3810                /* If necessary, advance to next segment in register
3811                   contents.  */
3812                while (d2 == dend2)
3813                  {
3814                    if (dend2 == end_match_2) break;
3815                    if (dend2 == regend[regno]) break;
3816
3817                    /* End of string1 => advance to string2. */
3818                    d2 = string2;
3819                    dend2 = regend[regno];
3820                  }
3821                /* At end of register contents => success */
3822                if (d2 == dend2) break;
3823
3824                /* If necessary, advance to next segment in data.  */
3825                PREFETCH ();
3826
3827                /* How many characters left in this segment to match.  */
3828                mcnt = dend - d;
3829               
3830                /* Want how many consecutive characters we can match in
3831                   one shot, so, if necessary, adjust the count.  */
3832                if (mcnt > dend2 - d2)
3833                  mcnt = dend2 - d2;
3834                 
3835                /* Compare that many; failure if mismatch, else move
3836                   past them.  */
3837                if (translate 
3838                    ? bcmp_translate (d, d2, mcnt, translate) 
3839                    : bcmp (d, d2, mcnt))
3840                  goto fail;
3841                d += mcnt, d2 += mcnt;
3842              }
3843          }
3844          break;
3845
3846
3847        /* begline matches the empty string at the beginning of the string
3848           (unless `not_bol' is set in `bufp'), and, if
3849           `newline_anchor' is set, after newlines.  */
3850        case begline:
3851          DEBUG_PRINT1 ("EXECUTING begline.\n");
3852         
3853          if (AT_STRINGS_BEG (d))
3854            {
3855              if (!bufp->not_bol) break;
3856            }
3857          else if (d[-1] == '\n' && bufp->newline_anchor)
3858            {
3859              break;
3860            }
3861          /* In all other cases, we fail.  */
3862          goto fail;
3863
3864
3865        /* endline is the dual of begline.  */
3866        case endline:
3867          DEBUG_PRINT1 ("EXECUTING endline.\n");
3868
3869          if (AT_STRINGS_END (d))
3870            {
3871              if (!bufp->not_eol) break;
3872            }
3873         
3874          /* We have to ``prefetch'' the next character.  */
3875          else if ((d == end1 ? *string2 : *d) == '\n'
3876                   && bufp->newline_anchor)
3877            {
3878              break;
3879            }
3880          goto fail;
3881
3882
3883        /* Match at the very beginning of the data.  */
3884        case begbuf:
3885          DEBUG_PRINT1 ("EXECUTING begbuf.\n");
3886          if (AT_STRINGS_BEG (d))
3887            break;
3888          goto fail;
3889
3890
3891        /* Match at the very end of the data.  */
3892        case endbuf:
3893          DEBUG_PRINT1 ("EXECUTING endbuf.\n");
3894          if (AT_STRINGS_END (d))
3895            break;
3896          goto fail;
3897
3898
3899        /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
3900           pushes NULL as the value for the string on the stack.  Then
3901           `pop_failure_point' will keep the current value for the
3902           string, instead of restoring it.  To see why, consider
3903           matching `foo\nbar' against `.*\n'.  The .* matches the foo;
3904           then the . fails against the \n.  But the next thing we want
3905           to do is match the \n against the \n; if we restored the
3906           string value, we would be back at the foo.
3907           
3908           Because this is used only in specific cases, we don't need to
3909           check all the things that `on_failure_jump' does, to make
3910           sure the right things get saved on the stack.  Hence we don't
3911           share its code.  The only reason to push anything on the
3912           stack at all is that otherwise we would have to change
3913           `anychar's code to do something besides goto fail in this
3914           case; that seems worse than this.  */
3915        case on_failure_keep_string_jump:
3916          DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
3917         
3918          EXTRACT_NUMBER_AND_INCR (mcnt, p);
3919          DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
3920
3921          PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
3922          break;
3923
3924
3925        /* Uses of on_failure_jump:
3926       
3927           Each alternative starts with an on_failure_jump that points
3928           to the beginning of the next alternative.  Each alternative
3929           except the last ends with a jump that in effect jumps past
3930           the rest of the alternatives.  (They really jump to the
3931           ending jump of the following alternative, because tensioning
3932           these jumps is a hassle.)
3933
3934           Repeats start with an on_failure_jump that points past both
3935           the repetition text and either the following jump or
3936           pop_failure_jump back to this on_failure_jump.  */
3937        case on_failure_jump:
3938        on_failure:
3939          DEBUG_PRINT1 ("EXECUTING on_failure_jump");
3940
3941          EXTRACT_NUMBER_AND_INCR (mcnt, p);
3942          DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
3943
3944          /* If this on_failure_jump comes right before a group (i.e.,
3945             the original * applied to a group), save the information
3946             for that group and all inner ones, so that if we fail back
3947             to this point, the group's information will be correct.
3948             For example, in \(a*\)*\1, we need the preceding group,
3949             and in \(\(a*\)b*\)\2, we need the inner group.  */
3950
3951          /* We can't use `p' to check ahead because we push
3952             a failure point to `p + mcnt' after we do this.  */
3953          p1 = p;
3954
3955          /* We need to skip no_op's before we look for the
3956             start_memory in case this on_failure_jump is happening as
3957             the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3958             against aba.  */
3959          while (p1 < pend && (re_opcode_t) *p1 == no_op)
3960            p1++;
3961
3962          if (p1 < pend && (re_opcode_t) *p1 == start_memory)
3963            {
3964              /* We have a new highest active register now.  This will
3965                 get reset at the start_memory we are about to get to,
3966                 but we will have saved all the registers relevant to
3967                 this repetition op, as described above.  */
3968              highest_active_reg = *(p1 + 1) + *(p1 + 2);
3969              if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3970                lowest_active_reg = *(p1 + 1);
3971            }
3972
3973          DEBUG_PRINT1 (":\n");
3974          PUSH_FAILURE_POINT (p + mcnt, d, -2);
3975          break;
3976
3977
3978        /* A smart repeat ends with `maybe_pop_jump'.
3979           We change it to either `pop_failure_jump' or `jump'.  */
3980        case maybe_pop_jump:
3981          EXTRACT_NUMBER_AND_INCR (mcnt, p);
3982          DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
3983          {
3984            register unsigned char *p2 = p;
3985
3986            /* Compare the beginning of the repeat with what in the
3987               pattern follows its end. If we can establish that there
3988               is nothing that they would both match, i.e., that we
3989               would have to backtrack because of (as in, e.g., `a*a')
3990               then we can change to pop_failure_jump, because we'll
3991               never have to backtrack.
3992               
3993               This is not true in the case of alternatives: in
3994               `(a|ab)*' we do need to backtrack to the `ab' alternative
3995               (e.g., if the string was `ab').  But instead of trying to
3996               detect that here, the alternative has put on a dummy
3997               failure point which is what we will end up popping.  */
3998
3999            /* Skip over open/close-group commands.  */
4000            while (p2 + 2 < pend
4001                   && ((re_opcode_t) *p2 == stop_memory
4002                       || (re_opcode_t) *p2 == start_memory))
4003              p2 += 3;                  /* Skip over args, too.  */
4004
4005            /* If we're at the end of the pattern, we can change.  */
4006            if (p2 == pend)
4007              {
4008                /* Consider what happens when matching ":\(.*\)"
4009                   against ":/".  I don't really understand this code
4010                   yet.  */
4011                p[-3] = (unsigned char) pop_failure_jump;
4012                DEBUG_PRINT1
4013                  ("  End of pattern: change to `pop_failure_jump'.\n");
4014              }
4015
4016            else if ((re_opcode_t) *p2 == exactn
4017                     || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4018              {
4019                register unsigned char c
4020                  = *p2 == (unsigned char) endline ? '\n' : p2[2];
4021                p1 = p + mcnt;
4022
4023                /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4024                   to the `maybe_finalize_jump' of this case.  Examine what
4025                   follows.  */
4026                if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4027                  {
4028                    p[-3] = (unsigned char) pop_failure_jump;
4029                    DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
4030                                  c, p1[5]);
4031                  }
4032                 
4033                else if ((re_opcode_t) p1[3] == charset
4034                         || (re_opcode_t) p1[3] == charset_not)
4035                  {
4036                    int not = (re_opcode_t) p1[3] == charset_not;
4037                   
4038                    if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4039                        && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4040                      not = !not;
4041
4042                    /* `not' is equal to 1 if c would match, which means
4043                        that we can't change to pop_failure_jump.  */
4044                    if (!not)
4045                      {
4046                        p[-3] = (unsigned char) pop_failure_jump;
4047                        DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
4048                      }
4049                  }
4050              }
4051          }
4052          p -= 2;               /* Point at relative address again.  */
4053          if ((re_opcode_t) p[-1] != pop_failure_jump)
4054            {
4055              p[-1] = (unsigned char) jump;
4056              DEBUG_PRINT1 ("  Match => jump.\n");
4057              goto unconditional_jump;
4058            }
4059        /* Note fall through.  */
4060
4061
4062        /* The end of a simple repeat has a pop_failure_jump back to
4063           its matching on_failure_jump, where the latter will push a
4064           failure point.  The pop_failure_jump takes off failure
4065           points put on by this pop_failure_jump's matching
4066           on_failure_jump; we got through the pattern to here from the
4067           matching on_failure_jump, so didn't fail.  */
4068        case pop_failure_jump:
4069          {
4070            /* We need to pass separate storage for the lowest and
4071               highest registers, even though we don't care about the
4072               actual values.  Otherwise, we will restore only one
4073               register from the stack, since lowest will == highest in
4074               `pop_failure_point'.  */
4075            unsigned dummy_low_reg, dummy_high_reg;
4076            unsigned char *pdummy;
4077            const char *sdummy;
4078
4079            DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4080            POP_FAILURE_POINT (sdummy, pdummy,
4081                               dummy_low_reg, dummy_high_reg,
4082                               reg_dummy, reg_dummy, reg_info_dummy);
4083          }
4084          /* Note fall through.  */
4085
4086         
4087        /* Unconditionally jump (without popping any failure points).  */
4088        case jump:
4089        unconditional_jump:
4090          EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
4091          DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4092          p += mcnt;                            /* Do the jump.  */
4093          DEBUG_PRINT2 ("(to 0x%x).\n", p);
4094          break;
4095
4096       
4097        /* We need this opcode so we can detect where alternatives end
4098           in `group_match_null_string_p' et al.  */
4099        case jump_past_alt:
4100          DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4101          goto unconditional_jump;
4102
4103
4104        /* Normally, the on_failure_jump pushes a failure point, which
4105           then gets popped at pop_failure_jump.  We will end up at
4106           pop_failure_jump, also, and with a pattern of, say, `a+', we
4107           are skipping over the on_failure_jump, so we have to push
4108           something meaningless for pop_failure_jump to pop.  */
4109        case dummy_failure_jump:
4110          DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4111          /* It doesn't matter what we push for the string here.  What
4112             the code at `fail' tests is the value for the pattern.  */
4113          PUSH_FAILURE_POINT (0, 0, -2);
4114          goto unconditional_jump;
4115
4116
4117        /* At the end of an alternative, we need to push a dummy failure
4118           point in case we are followed by a `pop_failure_jump', because
4119           we don't want the failure point for the alternative to be
4120           popped.  For example, matching `(a|ab)*' against `aab'
4121           requires that we match the `ab' alternative.  */
4122        case push_dummy_failure:
4123          DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4124          /* See comments just above at `dummy_failure_jump' about the
4125             two zeroes.  */
4126          PUSH_FAILURE_POINT (0, 0, -2);
4127          break;
4128
4129        /* Have to succeed matching what follows at least n times.
4130           After that, handle like `on_failure_jump'.  */
4131        case succeed_n:
4132          EXTRACT_NUMBER (mcnt, p + 2);
4133          DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4134
4135          assert (mcnt >= 0);
4136          /* Originally, this is how many times we HAVE to succeed.  */
4137          if (mcnt > 0)
4138            {
4139               mcnt--;
4140               p += 2;
4141               STORE_NUMBER_AND_INCR (p, mcnt);
4142               DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p, mcnt);
4143            }
4144          else if (mcnt == 0)
4145            {
4146              DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n", p+2);
4147              p[2] = (unsigned char) no_op;
4148              p[3] = (unsigned char) no_op;
4149              goto on_failure;
4150            }
4151          break;
4152       
4153        case jump_n:
4154          EXTRACT_NUMBER (mcnt, p + 2);
4155          DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4156
4157          /* Originally, this is how many times we CAN jump.  */
4158          if (mcnt)
4159            {
4160               mcnt--;
4161               STORE_NUMBER (p + 2, mcnt);
4162               goto unconditional_jump;     
4163            }
4164          /* If don't have to jump any more, skip over the rest of command.  */
4165          else     
4166            p += 4;                 
4167          break;
4168       
4169        case set_number_at:
4170          {
4171            DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4172
4173            EXTRACT_NUMBER_AND_INCR (mcnt, p);
4174            p1 = p + mcnt;
4175            EXTRACT_NUMBER_AND_INCR (mcnt, p);
4176            DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
4177            STORE_NUMBER (p1, mcnt);
4178            break;
4179          }
4180
4181        case wordbound:
4182          DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4183          if (AT_WORD_BOUNDARY (d))
4184            break;
4185          goto fail;
4186
4187        case notwordbound:
4188          DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4189          if (AT_WORD_BOUNDARY (d))
4190            goto fail;
4191          break;
4192
4193        case wordbeg:
4194          DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4195          if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4196            break;
4197          goto fail;
4198
4199        case wordend:
4200          DEBUG_PRINT1 ("EXECUTING wordend.\n");
4201          if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4202              && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4203            break;
4204          goto fail;
4205
4206#ifdef emacs
4207#ifdef emacs19
4208        case before_dot:
4209          DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4210          if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4211            goto fail;
4212          break;
4213 
4214        case at_dot:
4215          DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4216          if (PTR_CHAR_POS ((unsigned char *) d) != point)
4217            goto fail;
4218          break;
4219 
4220        case after_dot:
4221          DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4222          if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4223            goto fail;
4224          break;
4225#else /* not emacs19 */
4226        case at_dot:
4227          DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4228          if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4229            goto fail;
4230          break;
4231#endif /* not emacs19 */
4232
4233        case syntaxspec:
4234          DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4235          mcnt = *p++;
4236          goto matchsyntax;
4237
4238        case wordchar:
4239          DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4240          mcnt = (int) Sword;
4241        matchsyntax:
4242          PREFETCH ();
4243          if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
4244            goto fail;
4245          SET_REGS_MATCHED ();
4246          break;
4247
4248        case notsyntaxspec:
4249          DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4250          mcnt = *p++;
4251          goto matchnotsyntax;
4252
4253        case notwordchar:
4254          DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4255          mcnt = (int) Sword;
4256        matchnotsyntax:
4257          PREFETCH ();
4258          if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
4259            goto fail;
4260          SET_REGS_MATCHED ();
4261          break;
4262
4263#else /* not emacs */
4264        case wordchar:
4265          DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4266          PREFETCH ();
4267          if (!WORDCHAR_P (d))
4268            goto fail;
4269          SET_REGS_MATCHED ();
4270          d++;
4271          break;
4272         
4273        case notwordchar:
4274          DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4275          PREFETCH ();
4276          if (WORDCHAR_P (d))
4277            goto fail;
4278          SET_REGS_MATCHED ();
4279          d++;
4280          break;
4281#endif /* not emacs */
4282         
4283        default:
4284          abort ();
4285        }
4286      continue;  /* Successfully executed one pattern command; keep going.  */
4287
4288
4289    /* We goto here if a matching operation fails. */
4290    fail:
4291      if (!FAIL_STACK_EMPTY ())
4292        { /* A restart point is known.  Restore to that state.  */
4293          DEBUG_PRINT1 ("\nFAIL:\n");
4294          POP_FAILURE_POINT (d, p,
4295                             lowest_active_reg, highest_active_reg,
4296                             regstart, regend, reg_info);
4297
4298          /* If this failure point is a dummy, try the next one.  */
4299          if (!p)
4300            goto fail;
4301
4302          /* If we failed to the end of the pattern, don't examine *p.  */
4303          assert (p <= pend);
4304          if (p < pend)
4305            {
4306              boolean is_a_jump_n = false;
4307             
4308              /* If failed to a backwards jump that's part of a repetition
4309                 loop, need to pop this failure point and use the next one.  */
4310              switch ((re_opcode_t) *p)
4311                {
4312                case jump_n:
4313                  is_a_jump_n = true;
4314                case maybe_pop_jump:
4315                case pop_failure_jump:
4316                case jump:
4317                  p1 = p + 1;
4318                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4319                  p1 += mcnt;   
4320
4321                  if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4322                      || (!is_a_jump_n
4323                          && (re_opcode_t) *p1 == on_failure_jump))
4324                    goto fail;
4325                  break;
4326                default:
4327                  /* do nothing */ ;
4328                }
4329            }
4330
4331          if (d >= string1 && d <= end1)
4332            dend = end_match_1;
4333        }
4334      else
4335        break;   /* Matching at this starting point really fails.  */
4336    } /* for (;;) */
4337
4338  if (best_regs_set)
4339    goto restore_best_regs;
4340
4341  FREE_VARIABLES ();
4342
4343  return -1;                            /* Failure to match.  */
4344} /* re_match_2 */
4345
4346/* Subroutine definitions for re_match_2.  */
4347
4348
4349/* We are passed P pointing to a register number after a start_memory.
4350   
4351   Return true if the pattern up to the corresponding stop_memory can
4352   match the empty string, and false otherwise.
4353   
4354   If we find the matching stop_memory, sets P to point to one past its number.
4355   Otherwise, sets P to an undefined byte less than or equal to END.
4356
4357   We don't handle duplicates properly (yet).  */
4358
4359static boolean
4360group_match_null_string_p (p, end, reg_info)
4361    unsigned char **p, *end;
4362    register_info_type *reg_info;
4363{
4364  int mcnt;
4365  /* Point to after the args to the start_memory.  */
4366  unsigned char *p1 = *p + 2;
4367 
4368  while (p1 < end)
4369    {
4370      /* Skip over opcodes that can match nothing, and return true or
4371         false, as appropriate, when we get to one that can't, or to the
4372         matching stop_memory.  */
4373     
4374      switch ((re_opcode_t) *p1)
4375        {
4376        /* Could be either a loop or a series of alternatives.  */
4377        case on_failure_jump:
4378          p1++;
4379          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4380         
4381          /* If the next operation is not a jump backwards in the
4382             pattern.  */
4383
4384          if (mcnt >= 0)
4385            {
4386              /* Go through the on_failure_jumps of the alternatives,
4387                 seeing if any of the alternatives cannot match nothing.
4388                 The last alternative starts with only a jump,
4389                 whereas the rest start with on_failure_jump and end
4390                 with a jump, e.g., here is the pattern for `a|b|c':
4391
4392                 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4393                 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4394                 /exactn/1/c                                           
4395
4396                 So, we have to first go through the first (n-1)
4397                 alternatives and then deal with the last one separately.  */
4398
4399
4400              /* Deal with the first (n-1) alternatives, which start
4401                 with an on_failure_jump (see above) that jumps to right
4402                 past a jump_past_alt.  */
4403
4404              while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4405                {
4406                  /* `mcnt' holds how many bytes long the alternative
4407                     is, including the ending `jump_past_alt' and
4408                     its number.  */
4409
4410                  if (!alt_match_null_string_p (p1, p1 + mcnt - 3, 
4411                                                      reg_info))
4412                    return false;
4413
4414                  /* Move to right after this alternative, including the
4415                     jump_past_alt.  */
4416                  p1 += mcnt;   
4417
4418                  /* Break if it's the beginning of an n-th alternative
4419                     that doesn't begin with an on_failure_jump.  */
4420                  if ((re_opcode_t) *p1 != on_failure_jump)
4421                    break;
4422               
4423                  /* Still have to check that it's not an n-th
4424                     alternative that starts with an on_failure_jump.  */
4425                  p1++;
4426                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4427                  if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4428                    {
4429                      /* Get to the beginning of the n-th alternative.  */
4430                      p1 -= 3;
4431                      break;
4432                    }
4433                }
4434
4435              /* Deal with the last alternative: go back and get number
4436                 of the `jump_past_alt' just before it.  `mcnt' contains
4437                 the length of the alternative.  */
4438              EXTRACT_NUMBER (mcnt, p1 - 2);
4439
4440              if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4441                return false;
4442
4443              p1 += mcnt;       /* Get past the n-th alternative.  */
4444            } /* if mcnt > 0 */
4445          break;
4446
4447         
4448        case stop_memory:
4449          assert (p1[1] == **p);
4450          *p = p1 + 2;
4451          return true;
4452
4453       
4454        default: 
4455          if (!common_op_match_null_string_p (&p1, end, reg_info))
4456            return false;
4457        }
4458    } /* while p1 < end */
4459
4460  return false;
4461} /* group_match_null_string_p */
4462
4463
4464/* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4465   It expects P to be the first byte of a single alternative and END one
4466   byte past the last. The alternative can contain groups.  */
4467   
4468static boolean
4469alt_match_null_string_p (p, end, reg_info)
4470    unsigned char *p, *end;
4471    register_info_type *reg_info;
4472{
4473  int mcnt;
4474  unsigned char *p1 = p;
4475 
4476  while (p1 < end)
4477    {
4478      /* Skip over opcodes that can match nothing, and break when we get
4479         to one that can't.  */
4480     
4481      switch ((re_opcode_t) *p1)
4482        {
4483        /* It's a loop.  */
4484        case on_failure_jump:
4485          p1++;
4486          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4487          p1 += mcnt;
4488          break;
4489         
4490        default: 
4491          if (!common_op_match_null_string_p (&p1, end, reg_info))
4492            return false;
4493        }
4494    }  /* while p1 < end */
4495
4496  return true;
4497} /* alt_match_null_string_p */
4498
4499
4500/* Deals with the ops common to group_match_null_string_p and
4501   alt_match_null_string_p. 
4502   
4503   Sets P to one after the op and its arguments, if any.  */
4504
4505static boolean
4506common_op_match_null_string_p (p, end, reg_info)
4507    unsigned char **p, *end;
4508    register_info_type *reg_info;
4509{
4510  int mcnt;
4511  boolean ret;
4512  int reg_no;
4513  unsigned char *p1 = *p;
4514
4515  switch ((re_opcode_t) *p1++)
4516    {
4517    case no_op:
4518    case begline:
4519    case endline:
4520    case begbuf:
4521    case endbuf:
4522    case wordbeg:
4523    case wordend:
4524    case wordbound:
4525    case notwordbound:
4526#ifdef emacs
4527    case before_dot:
4528    case at_dot:
4529    case after_dot:
4530#endif
4531      break;
4532
4533    case start_memory:
4534      reg_no = *p1;
4535      assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4536      ret = group_match_null_string_p (&p1, end, reg_info);
4537     
4538      /* Have to set this here in case we're checking a group which
4539         contains a group and a back reference to it.  */
4540
4541      if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4542        REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4543
4544      if (!ret)
4545        return false;
4546      break;
4547         
4548    /* If this is an optimized succeed_n for zero times, make the jump.  */
4549    case jump:
4550      EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4551      if (mcnt >= 0)
4552        p1 += mcnt;
4553      else
4554        return false;
4555      break;
4556
4557    case succeed_n:
4558      /* Get to the number of times to succeed.  */
4559      p1 += 2;         
4560      EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4561
4562      if (mcnt == 0)
4563        {
4564          p1 -= 4;
4565          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4566          p1 += mcnt;
4567        }
4568      else
4569        return false;
4570      break;
4571
4572    case duplicate:
4573      if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
4574        return false;
4575      break;
4576
4577    case set_number_at:
4578      p1 += 4;
4579
4580    default:
4581      /* All other opcodes mean we cannot match the empty string.  */
4582      return false;
4583  }
4584
4585  *p = p1;
4586  return true;
4587} /* common_op_match_null_string_p */
4588
4589
4590/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
4591   bytes; nonzero otherwise.  */
4592   
4593static int
4594bcmp_translate (s1, s2, len, translate)
4595     unsigned char *s1, *s2;
4596     register int len;
4597     char *translate;
4598{
4599  register unsigned char *p1 = s1, *p2 = s2;
4600  while (len)
4601    {
4602      if (translate[*p1++] != translate[*p2++]) return 1;
4603      len--;
4604    }
4605  return 0;
4606}
4607
4608/* Entry points for GNU code.  */
4609
4610/* re_compile_pattern is the GNU regular expression compiler: it
4611   compiles PATTERN (of length SIZE) and puts the result in BUFP.
4612   Returns 0 if the pattern was valid, otherwise an error string.
4613   
4614   Assumes the `allocated' (and perhaps `buffer') and `translate' fields
4615   are set in BUFP on entry.
4616   
4617   We call regex_compile to do the actual compilation.  */
4618
4619const char *
4620re_compile_pattern (pattern, length, bufp)
4621     const char *pattern;
4622     int length;
4623     struct re_pattern_buffer *bufp;
4624{
4625  reg_errcode_t ret;
4626 
4627  /* GNU code is written to assume at least RE_NREGS registers will be set
4628     (and at least one extra will be -1).  */
4629  bufp->regs_allocated = REGS_UNALLOCATED;
4630 
4631  /* And GNU code determines whether or not to get register information
4632     by passing null for the REGS argument to re_match, etc., not by
4633     setting no_sub.  */
4634  bufp->no_sub = 0;
4635 
4636  /* Match anchors at newline.  */
4637  bufp->newline_anchor = 1;
4638 
4639  ret = regex_compile (pattern, length, re_syntax_options, bufp);
4640
4641  return re_error_msg[(int) ret];
4642}     
4643
4644/* Entry points compatible with 4.2 BSD regex library.  We don't define
4645   them if this is an Emacs or POSIX compilation.  */
4646
4647#if !defined (emacs) && !defined (_POSIX_SOURCE)
4648
4649/* BSD has one and only one pattern buffer.  */
4650static struct re_pattern_buffer re_comp_buf;
4651
4652char *
4653re_comp (s)
4654    const char *s;
4655{
4656  reg_errcode_t ret;
4657 
4658  if (!s)
4659    {
4660      if (!re_comp_buf.buffer)
4661        return "No previous regular expression";
4662      return 0;
4663    }
4664
4665  if (!re_comp_buf.buffer)
4666    {
4667      re_comp_buf.buffer = (unsigned char *) malloc (200);
4668      if (re_comp_buf.buffer == NULL)
4669        return "Memory exhausted";
4670      re_comp_buf.allocated = 200;
4671
4672      re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
4673      if (re_comp_buf.fastmap == NULL)
4674        return "Memory exhausted";
4675    }
4676
4677  /* Since `re_exec' always passes NULL for the `regs' argument, we
4678     don't need to initialize the pattern buffer fields which affect it.  */
4679
4680  /* Match anchors at newlines.  */
4681  re_comp_buf.newline_anchor = 1;
4682
4683  ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
4684 
4685  /* Yes, we're discarding `const' here.  */
4686  return (char *) re_error_msg[(int) ret];
4687}
4688
4689
4690int
4691re_exec (s)
4692    const char *s;
4693{
4694  const int len = strlen (s);
4695  return
4696    0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
4697}
4698#endif /* not emacs and not _POSIX_SOURCE */
4699
4700/* POSIX.2 functions.  Don't define these for Emacs.  */
4701
4702#ifndef emacs
4703
4704/* regcomp takes a regular expression as a string and compiles it.
4705
4706   PREG is a regex_t *.  We do not expect any fields to be initialized,
4707   since POSIX says we shouldn't.  Thus, we set
4708
4709     `buffer' to the compiled pattern;
4710     `used' to the length of the compiled pattern;
4711     `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4712       REG_EXTENDED bit in CFLAGS is set; otherwise, to
4713       RE_SYNTAX_POSIX_BASIC;
4714     `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4715     `fastmap' and `fastmap_accurate' to zero;
4716     `re_nsub' to the number of subexpressions in PATTERN.
4717
4718   PATTERN is the address of the pattern string.
4719
4720   CFLAGS is a series of bits which affect compilation.
4721
4722     If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4723     use POSIX basic syntax.
4724
4725     If REG_NEWLINE is set, then . and [^...] don't match newline.
4726     Also, regexec will try a match beginning after every newline.
4727
4728     If REG_ICASE is set, then we considers upper- and lowercase
4729     versions of letters to be equivalent when matching.
4730
4731     If REG_NOSUB is set, then when PREG is passed to regexec, that
4732     routine will report only success or failure, and nothing about the
4733     registers.
4734
4735   It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
4736   the return codes and their meanings.)  */
4737
4738int
4739my_regcomp (preg, pattern, cflags)
4740    regex_t *preg;
4741    const char *pattern; 
4742    int cflags;
4743{
4744  reg_errcode_t ret;
4745  unsigned syntax
4746    = (cflags & REG_EXTENDED) ?
4747      RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4748
4749  /* regex_compile will allocate the space for the compiled pattern.  */
4750  preg->buffer = 0;
4751  preg->allocated = 0;
4752 
4753  /* Don't bother to use a fastmap when searching.  This simplifies the
4754     REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4755     characters after newlines into the fastmap.  This way, we just try
4756     every character.  */
4757  preg->fastmap = 0;
4758 
4759  if (cflags & REG_ICASE)
4760    {
4761      unsigned i;
4762     
4763      preg->translate = (char *) malloc (CHAR_SET_SIZE);
4764      if (preg->translate == NULL)
4765        return (int) REG_ESPACE;
4766
4767      /* Map uppercase characters to corresponding lowercase ones.  */
4768      for (i = 0; i < CHAR_SET_SIZE; i++)
4769        preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
4770    }
4771  else
4772    preg->translate = NULL;
4773
4774  /* If REG_NEWLINE is set, newlines are treated differently.  */
4775  if (cflags & REG_NEWLINE)
4776    { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
4777      syntax &= ~RE_DOT_NEWLINE;
4778      syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4779      /* It also changes the matching behavior.  */
4780      preg->newline_anchor = 1;
4781    }
4782  else
4783    preg->newline_anchor = 0;
4784
4785  preg->no_sub = !!(cflags & REG_NOSUB);
4786
4787  /* POSIX says a null character in the pattern terminates it, so we
4788     can use strlen here in compiling the pattern.  */
4789  ret = regex_compile (pattern, strlen (pattern), syntax, preg);
4790 
4791  /* POSIX doesn't distinguish between an unmatched open-group and an
4792     unmatched close-group: both are REG_EPAREN.  */
4793  if (ret == REG_ERPAREN) ret = REG_EPAREN;
4794 
4795  return (int) ret;
4796}
4797
4798
4799/* regexec searches for a given pattern, specified by PREG, in the
4800   string STRING.
4801   
4802   If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4803   `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
4804   least NMATCH elements, and we set them to the offsets of the
4805   corresponding matched substrings.
4806   
4807   EFLAGS specifies `execution flags' which affect matching: if
4808   REG_NOTBOL is set, then ^ does not match at the beginning of the
4809   string; if REG_NOTEOL is set, then $ does not match at the end.
4810   
4811   We return 0 if we find a match and REG_NOMATCH if not.  */
4812
4813int
4814my_regexec (preg, string, nmatch, pmatch, eflags)
4815    const regex_t *preg;
4816    const char *string; 
4817    size_t nmatch; 
4818    regmatch_t pmatch[]; 
4819    int eflags;
4820{
4821  int ret;
4822  struct re_registers regs;
4823  regex_t private_preg;
4824  int len = strlen (string);
4825  boolean want_reg_info = !preg->no_sub && nmatch > 0;
4826
4827  private_preg = *preg;
4828 
4829  private_preg.not_bol = !!(eflags & REG_NOTBOL);
4830  private_preg.not_eol = !!(eflags & REG_NOTEOL);
4831 
4832  /* The user has told us exactly how many registers to return
4833     information about, via `nmatch'.  We have to pass that on to the
4834     matching routines.  */
4835  private_preg.regs_allocated = REGS_FIXED;
4836 
4837  if (want_reg_info)
4838    {
4839      regs.num_regs = nmatch;
4840      regs.start = TALLOC (nmatch, regoff_t);
4841      regs.end = TALLOC (nmatch, regoff_t);
4842      if (regs.start == NULL || regs.end == NULL)
4843        return (int) REG_NOMATCH;
4844    }
4845
4846  /* Perform the searching operation.  */
4847  ret = re_search (&private_preg, string, len,
4848                   /* start: */ 0, /* range: */ len,
4849                   want_reg_info ? &regs : (struct re_registers *) 0);
4850 
4851  /* Copy the register information to the POSIX structure.  */
4852  if (want_reg_info)
4853    {
4854      if (ret >= 0)
4855        {
4856          unsigned r;
4857
4858          for (r = 0; r < nmatch; r++)
4859            {
4860              pmatch[r].rm_so = regs.start[r];
4861              pmatch[r].rm_eo = regs.end[r];
4862            }
4863        }
4864
4865      /* If we needed the temporary register info, free the space now.  */
4866      free (regs.start);
4867      free (regs.end);
4868    }
4869
4870  /* We want zero return to mean success, unlike `re_search'.  */
4871  return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
4872}
4873
4874
4875/* Returns a message corresponding to an error code, ERRCODE, returned
4876   from either regcomp or regexec.   We don't use PREG here.  */
4877
4878size_t
4879my_regerror (errcode, preg, errbuf, errbuf_size)
4880    int errcode;
4881    const regex_t *preg;
4882    char *errbuf;
4883    size_t errbuf_size;
4884{
4885  const char *msg;
4886  size_t msg_size;
4887
4888  if (errcode < 0
4889      || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
4890    /* Only error codes returned by the rest of the code should be passed
4891       to this routine.  If we are given anything else, or if other regex
4892       code generates an invalid error code, then the program has a bug.
4893       Dump core so we can fix it.  */
4894    abort ();
4895
4896  msg = re_error_msg[errcode];
4897
4898  /* POSIX doesn't require that we do anything in this case, but why
4899     not be nice.  */
4900  if (! msg)
4901    msg = "Success";
4902
4903  msg_size = strlen (msg) + 1; /* Includes the null.  */
4904 
4905  if (errbuf_size != 0)
4906    {
4907      if (msg_size > errbuf_size)
4908        {
4909          strncpy (errbuf, msg, errbuf_size - 1);
4910          errbuf[errbuf_size - 1] = 0;
4911        }
4912      else
4913        strcpy (errbuf, msg);
4914    }
4915
4916  return msg_size;
4917}
4918
4919
4920/* Free dynamically allocated space used by PREG.  */
4921
4922void
4923my_regfree (preg)
4924    regex_t *preg;
4925{
4926  if (preg->buffer != NULL)
4927    free (preg->buffer);
4928  preg->buffer = NULL;
4929 
4930  preg->allocated = 0;
4931  preg->used = 0;
4932
4933  if (preg->fastmap != NULL)
4934    free (preg->fastmap);
4935  preg->fastmap = NULL;
4936  preg->fastmap_accurate = 0;
4937
4938  if (preg->translate != NULL)
4939    free (preg->translate);
4940  preg->translate = NULL;
4941}
4942
4943#endif /* not emacs  */
4944
4945/*
4946Local variables:
4947make-backup-files: t
4948version-control: t
4949trim-versions-without-asking: nil
4950End:
4951*/
Note: See TracBrowser for help on using the browser.