Merge from vendor branch TEXINFO:
[dragonfly.git] / lib / libc / regex / engine.c
1 /*-
2  * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3  * Copyright (c) 1992, 1993, 1994
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Henry Spencer.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      @(#)engine.c    8.5 (Berkeley) 3/20/94
38  *
39  * $FreeBSD: src/lib/libc/regex/engine.c,v 1.5.8.1 2000/07/31 06:30:37 dcs Exp $
40  * $DragonFly: src/lib/libc/regex/engine.c,v 1.6 2005/01/08 19:17:01 dillon Exp $
41  */
42
43 /*
44  * The matching engine and friends.  This file is #included by regexec.c
45  * after suitable #defines of a variety of macros used herein, so that
46  * different state representations can be used without duplicating masses
47  * of code.
48  */
49
50 #ifdef SNAMES
51 #define matcher smatcher
52 #define fast    sfast
53 #define slow    sslow
54 #define dissect sdissect
55 #define backref sbackref
56 #define step    sstep
57 #define print   sprint
58 #define at      sat
59 #define match   smat
60 #endif
61 #ifdef LNAMES
62 #define matcher lmatcher
63 #define fast    lfast
64 #define slow    lslow
65 #define dissect ldissect
66 #define backref lbackref
67 #define step    lstep
68 #define print   lprint
69 #define at      lat
70 #define match   lmat
71 #endif
72
73 /* another structure passed up and down to avoid zillions of parameters */
74 struct match {
75         struct re_guts *g;
76         int eflags;
77         regmatch_t *pmatch;     /* [nsub+1] (0 element unused) */
78         char *offp;             /* offsets work from here */
79         char *beginp;           /* start of string -- virtual NUL precedes */
80         char *endp;             /* end of string -- virtual NUL here */
81         char *coldp;            /* can be no match starting before here */
82         char **lastpos;         /* [nplus+1] */
83         STATEVARS;
84         states st;              /* current states */
85         states fresh;           /* states for a fresh start */
86         states tmp;             /* temporary */
87         states empty;           /* empty set of states */
88 };
89
90 /* ========= begin header generated by ./mkh ========= */
91 #ifdef __cplusplus
92 extern "C" {
93 #endif
94
95 /* === engine.c === */
96 static int matcher(struct re_guts *g, char *string, size_t nmatch, regmatch_t pmatch[], int eflags);
97 static char *dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst);
98 static char *backref(struct match *m, char *start, char *stop, sopno startst, sopno stopst, sopno lev);
99 static char *fast(struct match *m, char *start, char *stop, sopno startst, sopno stopst);
100 static char *slow(struct match *m, char *start, char *stop, sopno startst, sopno stopst);
101 static states step(struct re_guts *g, sopno start, sopno stop, states bef, int ch, states aft);
102 #define BOL     (OUT+1)
103 #define EOL     (BOL+1)
104 #define BOLEOL  (BOL+2)
105 #define NOTHING (BOL+3)
106 #define BOW     (BOL+4)
107 #define EOW     (BOL+5)
108 #define CODEMAX (BOL+5)         /* highest code used */
109 #define NONCHAR(c)      ((c) > CHAR_MAX)
110 #define NNONCHAR        (CODEMAX-CHAR_MAX)
111 #ifdef REDEBUG
112 static void print(struct match *m, char *caption, states st, int ch, FILE *d);
113 #endif
114 #ifdef REDEBUG
115 static void at(struct match *m, char *title, char *start, char *stop, sopno startst, sopno stopst);
116 #endif
117 #ifdef REDEBUG
118 static char *pchar(int ch);
119 #endif
120
121 #ifdef __cplusplus
122 }
123 #endif
124 /* ========= end header generated by ./mkh ========= */
125
126 #ifdef REDEBUG
127 #define SP(t, s, c)     print(m, t, s, c, stdout)
128 #define AT(t, p1, p2, s1, s2)   at(m, t, p1, p2, s1, s2)
129 #define NOTE(str)       { if (m->eflags&REG_TRACE) printf("=%s\n", (str)); }
130 #else
131 #define SP(t, s, c)     /* nothing */
132 #define AT(t, p1, p2, s1, s2)   /* nothing */
133 #define NOTE(s) /* nothing */
134 #endif
135
136 /*
137  - matcher - the actual matching engine
138  == static int matcher(struct re_guts *g, char *string, \
139  ==     size_t nmatch, regmatch_t pmatch[], int eflags);
140  */
141 static int                      /* 0 success, REG_NOMATCH failure */
142 matcher(struct re_guts *g, char *string, size_t nmatch, regmatch_t pmatch[],
143         int eflags)
144 {
145         char *endp;
146         int i;
147         struct match mv;
148         struct match *m = &mv;
149         char *dp;
150         const sopno gf = g->firststate+1;       /* +1 for OEND */
151         const sopno gl = g->laststate;
152         char *start;
153         char *stop;
154         /* Boyer-Moore algorithms variables */
155         char *pp;
156         int cj, mj;
157         char *mustfirst;
158         char *mustlast;
159         int *matchjump;
160         int *charjump;
161
162         /* simplify the situation where possible */
163         if (g->cflags&REG_NOSUB)
164                 nmatch = 0;
165         if (eflags&REG_STARTEND) {
166                 start = string + pmatch[0].rm_so;
167                 stop = string + pmatch[0].rm_eo;
168         } else {
169                 start = string;
170                 stop = start + strlen(start);
171         }
172         if (stop < start)
173                 return(REG_INVARG);
174
175         /* prescreening; this does wonders for this rather slow code */
176         if (g->must != NULL) {
177                 if (g->charjump != NULL && g->matchjump != NULL) {
178                         mustfirst = g->must;
179                         mustlast = g->must + g->mlen - 1;
180                         charjump = g->charjump;
181                         matchjump = g->matchjump;
182                         pp = mustlast;
183                         for (dp = start+g->mlen-1; dp < stop;) {
184                                 /* Fast skip non-matches */
185                                 while (dp < stop && charjump[*dp])
186                                         dp += charjump[*dp];
187
188                                 if (dp >= stop)
189                                         break;
190
191                                 /* Greedy matcher */
192                                 /* We depend on not being used for
193                                  * for strings of length 1
194                                  */
195                                 while (*--dp == *--pp && pp != mustfirst);
196
197                                 if (*dp == *pp)
198                                         break;
199
200                                 /* Jump to next possible match */
201                                 mj = matchjump[pp - mustfirst];
202                                 cj = charjump[*dp];
203                                 dp += (cj < mj ? mj : cj);
204                                 pp = mustlast;
205                         }
206                         if (pp != mustfirst)
207                                 return(REG_NOMATCH);
208                 } else {
209                         for (dp = start; dp < stop; dp++)
210                                 if (*dp == g->must[0] &&
211                                     stop - dp >= g->mlen &&
212                                     memcmp(dp, g->must, (size_t)g->mlen) == 0)
213                                         break;
214                         if (dp == stop)         /* we didn't find g->must */
215                                 return(REG_NOMATCH);
216                 }
217         }
218
219         /* match struct setup */
220         m->g = g;
221         m->eflags = eflags;
222         m->pmatch = NULL;
223         m->lastpos = NULL;
224         m->offp = string;
225         m->beginp = start;
226         m->endp = stop;
227         STATESETUP(m, 4);
228         SETUP(m->st);
229         SETUP(m->fresh);
230         SETUP(m->tmp);
231         SETUP(m->empty);
232         CLEAR(m->empty);
233
234         /* Adjust start according to moffset, to speed things up */
235         if (g->moffset > -1)
236                 start = ((dp - g->moffset) < start) ? start : dp - g->moffset;
237
238         /* this loop does only one repetition except for backrefs */
239         for (;;) {
240                 endp = fast(m, start, stop, gf, gl);
241                 if (endp == NULL) {             /* a miss */
242                         if (m->pmatch != NULL)
243                                 free((char *)m->pmatch);
244                         if (m->lastpos != NULL)
245                                 free((char *)m->lastpos);
246                         STATETEARDOWN(m);
247                         return(REG_NOMATCH);
248                 }
249                 if (nmatch == 0 && !g->backrefs)
250                         break;          /* no further info needed */
251
252                 /* where? */
253                 assert(m->coldp != NULL);
254                 for (;;) {
255                         NOTE("finding start");
256                         endp = slow(m, m->coldp, stop, gf, gl);
257                         if (endp != NULL)
258                                 break;
259                         assert(m->coldp < m->endp);
260                         m->coldp++;
261                 }
262                 if (nmatch == 1 && !g->backrefs)
263                         break;          /* no further info needed */
264
265                 /* oh my, he wants the subexpressions... */
266                 if (m->pmatch == NULL)
267                         m->pmatch = (regmatch_t *)malloc((m->g->nsub + 1) *
268                                                         sizeof(regmatch_t));
269                 if (m->pmatch == NULL) {
270                         STATETEARDOWN(m);
271                         return(REG_ESPACE);
272                 }
273                 for (i = 1; i <= m->g->nsub; i++)
274                         m->pmatch[i].rm_so = m->pmatch[i].rm_eo = -1;
275                 if (!g->backrefs && !(m->eflags&REG_BACKR)) {
276                         NOTE("dissecting");
277                         dp = dissect(m, m->coldp, endp, gf, gl);
278                 } else {
279                         if (g->nplus > 0 && m->lastpos == NULL)
280                                 m->lastpos = (char **)malloc((g->nplus+1) *
281                                                         sizeof(char *));
282                         if (g->nplus > 0 && m->lastpos == NULL) {
283                                 free(m->pmatch);
284                                 STATETEARDOWN(m);
285                                 return(REG_ESPACE);
286                         }
287                         NOTE("backref dissect");
288                         dp = backref(m, m->coldp, endp, gf, gl, (sopno)0);
289                 }
290                 if (dp != NULL)
291                         break;
292
293                 /* uh-oh... we couldn't find a subexpression-level match */
294                 assert(g->backrefs);    /* must be back references doing it */
295                 assert(g->nplus == 0 || m->lastpos != NULL);
296                 for (;;) {
297                         if (dp != NULL || endp <= m->coldp)
298                                 break;          /* defeat */
299                         NOTE("backoff");
300                         endp = slow(m, m->coldp, endp-1, gf, gl);
301                         if (endp == NULL)
302                                 break;          /* defeat */
303                         /* try it on a shorter possibility */
304 #ifndef NDEBUG
305                         for (i = 1; i <= m->g->nsub; i++) {
306                                 assert(m->pmatch[i].rm_so == -1);
307                                 assert(m->pmatch[i].rm_eo == -1);
308                         }
309 #endif
310                         NOTE("backoff dissect");
311                         dp = backref(m, m->coldp, endp, gf, gl, (sopno)0);
312                 }
313                 assert(dp == NULL || dp == endp);
314                 if (dp != NULL)         /* found a shorter one */
315                         break;
316
317                 /* despite initial appearances, there is no match here */
318                 NOTE("false alarm");
319                 start = m->coldp + 1;   /* recycle starting later */
320                 assert(start <= stop);
321         }
322
323         /* fill in the details if requested */
324         if (nmatch > 0) {
325                 pmatch[0].rm_so = m->coldp - m->offp;
326                 pmatch[0].rm_eo = endp - m->offp;
327         }
328         if (nmatch > 1) {
329                 assert(m->pmatch != NULL);
330                 for (i = 1; i < nmatch; i++)
331                         if (i <= m->g->nsub)
332                                 pmatch[i] = m->pmatch[i];
333                         else {
334                                 pmatch[i].rm_so = -1;
335                                 pmatch[i].rm_eo = -1;
336                         }
337         }
338
339         if (m->pmatch != NULL)
340                 free((char *)m->pmatch);
341         if (m->lastpos != NULL)
342                 free((char *)m->lastpos);
343         STATETEARDOWN(m);
344         return(0);
345 }
346
347 /*
348  - dissect - figure out what matched what, no back references
349  == static char *dissect(struct match *m, char *start, \
350  ==     char *stop, sopno startst, sopno stopst);
351  */
352 static char *                   /* == stop (success) always */
353 dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst)
354 {
355         int i;
356         sopno ss;               /* start sop of current subRE */
357         sopno es;               /* end sop of current subRE */
358         char *sp;               /* start of string matched by it */
359         char *stp;              /* string matched by it cannot pass here */
360         char *rest;             /* start of rest of string */
361         char *tail;             /* string unmatched by rest of RE */
362         sopno ssub;             /* start sop of subsubRE */
363         sopno esub;             /* end sop of subsubRE */
364         char *ssp;              /* start of string matched by subsubRE */
365         char *sep;              /* end of string matched by subsubRE */
366         char *oldssp;           /* previous ssp */
367         char *dp;
368
369         AT("diss", start, stop, startst, stopst);
370         sp = start;
371         for (ss = startst; ss < stopst; ss = es) {
372                 /* identify end of subRE */
373                 es = ss;
374                 switch (OP(m->g->strip[es])) {
375                 case OPLUS_:
376                 case OQUEST_:
377                         es += OPND(m->g->strip[es]);
378                         break;
379                 case OCH_:
380                         while (OP(m->g->strip[es]) != O_CH)
381                                 es += OPND(m->g->strip[es]);
382                         break;
383                 }
384                 es++;
385
386                 /* figure out what it matched */
387                 switch (OP(m->g->strip[ss])) {
388                 case OEND:
389                         assert(nope);
390                         break;
391                 case OCHAR:
392                         sp++;
393                         break;
394                 case OBOL:
395                 case OEOL:
396                 case OBOW:
397                 case OEOW:
398                         break;
399                 case OANY:
400                 case OANYOF:
401                         sp++;
402                         break;
403                 case OBACK_:
404                 case O_BACK:
405                         assert(nope);
406                         break;
407                 /* cases where length of match is hard to find */
408                 case OQUEST_:
409                         stp = stop;
410                         for (;;) {
411                                 /* how long could this one be? */
412                                 rest = slow(m, sp, stp, ss, es);
413                                 assert(rest != NULL);   /* it did match */
414                                 /* could the rest match the rest? */
415                                 tail = slow(m, rest, stop, es, stopst);
416                                 if (tail == stop)
417                                         break;          /* yes! */
418                                 /* no -- try a shorter match for this one */
419                                 stp = rest - 1;
420                                 assert(stp >= sp);      /* it did work */
421                         }
422                         ssub = ss + 1;
423                         esub = es - 1;
424                         /* did innards match? */
425                         if (slow(m, sp, rest, ssub, esub) != NULL) {
426                                 dp = dissect(m, sp, rest, ssub, esub);
427                                 assert(dp == rest);
428                         } else          /* no */
429                                 assert(sp == rest);
430                         sp = rest;
431                         break;
432                 case OPLUS_:
433                         stp = stop;
434                         for (;;) {
435                                 /* how long could this one be? */
436                                 rest = slow(m, sp, stp, ss, es);
437                                 assert(rest != NULL);   /* it did match */
438                                 /* could the rest match the rest? */
439                                 tail = slow(m, rest, stop, es, stopst);
440                                 if (tail == stop)
441                                         break;          /* yes! */
442                                 /* no -- try a shorter match for this one */
443                                 stp = rest - 1;
444                                 assert(stp >= sp);      /* it did work */
445                         }
446                         ssub = ss + 1;
447                         esub = es - 1;
448                         ssp = sp;
449                         oldssp = ssp;
450                         for (;;) {      /* find last match of innards */
451                                 sep = slow(m, ssp, rest, ssub, esub);
452                                 if (sep == NULL || sep == ssp)
453                                         break;  /* failed or matched null */
454                                 oldssp = ssp;   /* on to next try */
455                                 ssp = sep;
456                         }
457                         if (sep == NULL) {
458                                 /* last successful match */
459                                 sep = ssp;
460                                 ssp = oldssp;
461                         }
462                         assert(sep == rest);    /* must exhaust substring */
463                         assert(slow(m, ssp, sep, ssub, esub) == rest);
464                         dp = dissect(m, ssp, sep, ssub, esub);
465                         assert(dp == sep);
466                         sp = rest;
467                         break;
468                 case OCH_:
469                         stp = stop;
470                         for (;;) {
471                                 /* how long could this one be? */
472                                 rest = slow(m, sp, stp, ss, es);
473                                 assert(rest != NULL);   /* it did match */
474                                 /* could the rest match the rest? */
475                                 tail = slow(m, rest, stop, es, stopst);
476                                 if (tail == stop)
477                                         break;          /* yes! */
478                                 /* no -- try a shorter match for this one */
479                                 stp = rest - 1;
480                                 assert(stp >= sp);      /* it did work */
481                         }
482                         ssub = ss + 1;
483                         esub = ss + OPND(m->g->strip[ss]) - 1;
484                         assert(OP(m->g->strip[esub]) == OOR1);
485                         for (;;) {      /* find first matching branch */
486                                 if (slow(m, sp, rest, ssub, esub) == rest)
487                                         break;  /* it matched all of it */
488                                 /* that one missed, try next one */
489                                 assert(OP(m->g->strip[esub]) == OOR1);
490                                 esub++;
491                                 assert(OP(m->g->strip[esub]) == OOR2);
492                                 ssub = esub + 1;
493                                 esub += OPND(m->g->strip[esub]);
494                                 if (OP(m->g->strip[esub]) == OOR2)
495                                         esub--;
496                                 else
497                                         assert(OP(m->g->strip[esub]) == O_CH);
498                         }
499                         dp = dissect(m, sp, rest, ssub, esub);
500                         assert(dp == rest);
501                         sp = rest;
502                         break;
503                 case O_PLUS:
504                 case O_QUEST:
505                 case OOR1:
506                 case OOR2:
507                 case O_CH:
508                         assert(nope);
509                         break;
510                 case OLPAREN:
511                         i = OPND(m->g->strip[ss]);
512                         assert(0 < i && i <= m->g->nsub);
513                         m->pmatch[i].rm_so = sp - m->offp;
514                         break;
515                 case ORPAREN:
516                         i = OPND(m->g->strip[ss]);
517                         assert(0 < i && i <= m->g->nsub);
518                         m->pmatch[i].rm_eo = sp - m->offp;
519                         break;
520                 default:                /* uh oh */
521                         assert(nope);
522                         break;
523                 }
524         }
525
526         assert(sp == stop);
527         return(sp);
528 }
529
530 /*
531  - backref - figure out what matched what, figuring in back references
532  == static char *backref(struct match *m, char *start, \
533  ==     char *stop, sopno startst, sopno stopst, sopno lev);
534  */
535 static char *                   /* == stop (success) or NULL (failure) */
536 backref(struct match *m, char *start, char *stop, sopno startst, sopno stopst,
537         sopno lev)                      /* PLUS nesting level */
538 {
539         int i;
540         sopno ss;               /* start sop of current subRE */
541         char *sp;               /* start of string matched by it */
542         sopno ssub;             /* start sop of subsubRE */
543         sopno esub;             /* end sop of subsubRE */
544         char *ssp;              /* start of string matched by subsubRE */
545         char *dp;
546         size_t len;
547         int hard;
548         sop s;
549         regoff_t offsave;
550         cset *cs;
551
552         AT("back", start, stop, startst, stopst);
553         sp = start;
554
555         /* get as far as we can with easy stuff */
556         hard = 0;
557         for (ss = startst; !hard && ss < stopst; ss++)
558                 switch (OP(s = m->g->strip[ss])) {
559                 case OCHAR:
560                         if (sp == stop || *sp++ != (char)OPND(s))
561                                 return(NULL);
562                         break;
563                 case OANY:
564                         if (sp == stop)
565                                 return(NULL);
566                         sp++;
567                         break;
568                 case OANYOF:
569                         cs = &m->g->sets[OPND(s)];
570                         if (sp == stop || !CHIN(cs, *sp++))
571                                 return(NULL);
572                         break;
573                 case OBOL:
574                         if ( (sp == m->beginp && !(m->eflags&REG_NOTBOL)) ||
575                                         (sp < m->endp && *(sp-1) == '\n' &&
576                                                 (m->g->cflags&REG_NEWLINE)) )
577                                 { /* yes */ }
578                         else
579                                 return(NULL);
580                         break;
581                 case OEOL:
582                         if ( (sp == m->endp && !(m->eflags&REG_NOTEOL)) ||
583                                         (sp < m->endp && *sp == '\n' &&
584                                                 (m->g->cflags&REG_NEWLINE)) )
585                                 { /* yes */ }
586                         else
587                                 return(NULL);
588                         break;
589                 case OBOW:
590                         if (( (sp == m->beginp && !(m->eflags&REG_NOTBOL)) ||
591                                         (sp < m->endp && *(sp-1) == '\n' &&
592                                                 (m->g->cflags&REG_NEWLINE)) ||
593                                         (sp > m->beginp &&
594                                                         !ISWORD(*(sp-1))) ) &&
595                                         (sp < m->endp && ISWORD(*sp)) )
596                                 { /* yes */ }
597                         else
598                                 return(NULL);
599                         break;
600                 case OEOW:
601                         if (( (sp == m->endp && !(m->eflags&REG_NOTEOL)) ||
602                                         (sp < m->endp && *sp == '\n' &&
603                                                 (m->g->cflags&REG_NEWLINE)) ||
604                                         (sp < m->endp && !ISWORD(*sp)) ) &&
605                                         (sp > m->beginp && ISWORD(*(sp-1))) )
606                                 { /* yes */ }
607                         else
608                                 return(NULL);
609                         break;
610                 case O_QUEST:
611                         break;
612                 case OOR1:      /* matches null but needs to skip */
613                         ss++;
614                         s = m->g->strip[ss];
615                         do {
616                                 assert(OP(s) == OOR2);
617                                 ss += OPND(s);
618                         } while (OP(s = m->g->strip[ss]) != O_CH);
619                         /* note that the ss++ gets us past the O_CH */
620                         break;
621                 default:        /* have to make a choice */
622                         hard = 1;
623                         break;
624                 }
625         if (!hard) {            /* that was it! */
626                 if (sp != stop)
627                         return(NULL);
628                 return(sp);
629         }
630         ss--;                   /* adjust for the for's final increment */
631
632         /* the hard stuff */
633         AT("hard", sp, stop, ss, stopst);
634         s = m->g->strip[ss];
635         switch (OP(s)) {
636         case OBACK_:            /* the vilest depths */
637                 i = OPND(s);
638                 assert(0 < i && i <= m->g->nsub);
639                 if (m->pmatch[i].rm_eo == -1)
640                         return(NULL);
641                 assert(m->pmatch[i].rm_so != -1);
642                 len = m->pmatch[i].rm_eo - m->pmatch[i].rm_so;
643                 assert(stop - m->beginp >= len);
644                 if (sp > stop - len)
645                         return(NULL);   /* not enough left to match */
646                 ssp = m->offp + m->pmatch[i].rm_so;
647                 if (memcmp(sp, ssp, len) != 0)
648                         return(NULL);
649                 while (m->g->strip[ss] != SOP(O_BACK, i))
650                         ss++;
651                 return(backref(m, sp+len, stop, ss+1, stopst, lev));
652                 break;
653         case OQUEST_:           /* to null or not */
654                 dp = backref(m, sp, stop, ss+1, stopst, lev);
655                 if (dp != NULL)
656                         return(dp);     /* not */
657                 return(backref(m, sp, stop, ss+OPND(s)+1, stopst, lev));
658                 break;
659         case OPLUS_:
660                 assert(m->lastpos != NULL);
661                 assert(lev+1 <= m->g->nplus);
662                 m->lastpos[lev+1] = sp;
663                 return(backref(m, sp, stop, ss+1, stopst, lev+1));
664                 break;
665         case O_PLUS:
666                 if (sp == m->lastpos[lev])      /* last pass matched null */
667                         return(backref(m, sp, stop, ss+1, stopst, lev-1));
668                 /* try another pass */
669                 m->lastpos[lev] = sp;
670                 dp = backref(m, sp, stop, ss-OPND(s)+1, stopst, lev);
671                 if (dp == NULL)
672                         return(backref(m, sp, stop, ss+1, stopst, lev-1));
673                 else
674                         return(dp);
675                 break;
676         case OCH_:              /* find the right one, if any */
677                 ssub = ss + 1;
678                 esub = ss + OPND(s) - 1;
679                 assert(OP(m->g->strip[esub]) == OOR1);
680                 for (;;) {      /* find first matching branch */
681                         dp = backref(m, sp, stop, ssub, esub, lev);
682                         if (dp != NULL)
683                                 return(dp);
684                         /* that one missed, try next one */
685                         if (OP(m->g->strip[esub]) == O_CH)
686                                 return(NULL);   /* there is none */
687                         esub++;
688                         assert(OP(m->g->strip[esub]) == OOR2);
689                         ssub = esub + 1;
690                         esub += OPND(m->g->strip[esub]);
691                         if (OP(m->g->strip[esub]) == OOR2)
692                                 esub--;
693                         else
694                                 assert(OP(m->g->strip[esub]) == O_CH);
695                 }
696                 break;
697         case OLPAREN:           /* must undo assignment if rest fails */
698                 i = OPND(s);
699                 assert(0 < i && i <= m->g->nsub);
700                 offsave = m->pmatch[i].rm_so;
701                 m->pmatch[i].rm_so = sp - m->offp;
702                 dp = backref(m, sp, stop, ss+1, stopst, lev);
703                 if (dp != NULL)
704                         return(dp);
705                 m->pmatch[i].rm_so = offsave;
706                 return(NULL);
707                 break;
708         case ORPAREN:           /* must undo assignment if rest fails */
709                 i = OPND(s);
710                 assert(0 < i && i <= m->g->nsub);
711                 offsave = m->pmatch[i].rm_eo;
712                 m->pmatch[i].rm_eo = sp - m->offp;
713                 dp = backref(m, sp, stop, ss+1, stopst, lev);
714                 if (dp != NULL)
715                         return(dp);
716                 m->pmatch[i].rm_eo = offsave;
717                 return(NULL);
718                 break;
719         default:                /* uh oh */
720                 assert(nope);
721                 break;
722         }
723
724         /* "can't happen" */
725         assert(nope);
726         /* NOTREACHED */
727         return "shut up gcc";
728 }
729
730 /*
731  - fast - step through the string at top speed
732  == static char *fast(struct match *m, char *start, \
733  ==     char *stop, sopno startst, sopno stopst);
734  */
735 static char *                   /* where tentative match ended, or NULL */
736 fast(struct match *m, char *start, char *stop, sopno startst, sopno stopst)
737 {
738         states st = m->st;
739         states fresh = m->fresh;
740         states tmp = m->tmp;
741         char *p = start;
742         int c = (start == m->beginp) ? OUT : *(start-1);
743         int lastc;              /* previous c */
744         int flagch;
745         int i;
746         char *coldp;            /* last p after which no match was underway */
747
748         CLEAR(st);
749         SET1(st, startst);
750         st = step(m->g, startst, stopst, st, NOTHING, st);
751         ASSIGN(fresh, st);
752         SP("start", st, *p);
753         coldp = NULL;
754         for (;;) {
755                 /* next character */
756                 lastc = c;
757                 c = (p == m->endp) ? OUT : *p;
758                 if (EQ(st, fresh))
759                         coldp = p;
760
761                 /* is there an EOL and/or BOL between lastc and c? */
762                 flagch = '\0';
763                 i = 0;
764                 if ( (lastc == '\n' && m->g->cflags&REG_NEWLINE) ||
765                                 (lastc == OUT && !(m->eflags&REG_NOTBOL)) ) {
766                         flagch = BOL;
767                         i = m->g->nbol;
768                 }
769                 if ( (c == '\n' && m->g->cflags&REG_NEWLINE) ||
770                                 (c == OUT && !(m->eflags&REG_NOTEOL)) ) {
771                         flagch = (flagch == BOL) ? BOLEOL : EOL;
772                         i += m->g->neol;
773                 }
774                 if (i != 0) {
775                         for (; i > 0; i--)
776                                 st = step(m->g, startst, stopst, st, flagch, st);
777                         SP("boleol", st, c);
778                 }
779
780                 /* how about a word boundary? */
781                 if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) &&
782                                         (c != OUT && ISWORD(c)) ) {
783                         flagch = BOW;
784                 }
785                 if ( (lastc != OUT && ISWORD(lastc)) &&
786                                 (flagch == EOL || (c != OUT && !ISWORD(c))) ) {
787                         flagch = EOW;
788                 }
789                 if (flagch == BOW || flagch == EOW) {
790                         st = step(m->g, startst, stopst, st, flagch, st);
791                         SP("boweow", st, c);
792                 }
793
794                 /* are we done? */
795                 if (ISSET(st, stopst) || p == stop)
796                         break;          /* NOTE BREAK OUT */
797
798                 /* no, we must deal with this character */
799                 ASSIGN(tmp, st);
800                 ASSIGN(st, fresh);
801                 assert(c != OUT);
802                 st = step(m->g, startst, stopst, tmp, c, st);
803                 SP("aft", st, c);
804                 assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st));
805                 p++;
806         }
807
808         assert(coldp != NULL);
809         m->coldp = coldp;
810         if (ISSET(st, stopst))
811                 return(p+1);
812         else
813                 return(NULL);
814 }
815
816 /*
817  - slow - step through the string more deliberately
818  == static char *slow(struct match *m, char *start, \
819  ==     char *stop, sopno startst, sopno stopst);
820  */
821 static char *                   /* where it ended */
822 slow(struct match *m, char *start, char *stop, sopno startst, sopno stopst)
823 {
824         states st = m->st;
825         states empty = m->empty;
826         states tmp = m->tmp;
827         char *p = start;
828         int c = (start == m->beginp) ? OUT : *(start-1);
829         int lastc;              /* previous c */
830         int flagch;
831         int i;
832         char *matchp;           /* last p at which a match ended */
833
834         AT("slow", start, stop, startst, stopst);
835         CLEAR(st);
836         SET1(st, startst);
837         SP("sstart", st, *p);
838         st = step(m->g, startst, stopst, st, NOTHING, st);
839         matchp = NULL;
840         for (;;) {
841                 /* next character */
842                 lastc = c;
843                 c = (p == m->endp) ? OUT : *p;
844
845                 /* is there an EOL and/or BOL between lastc and c? */
846                 flagch = '\0';
847                 i = 0;
848                 if ( (lastc == '\n' && m->g->cflags&REG_NEWLINE) ||
849                                 (lastc == OUT && !(m->eflags&REG_NOTBOL)) ) {
850                         flagch = BOL;
851                         i = m->g->nbol;
852                 }
853                 if ( (c == '\n' && m->g->cflags&REG_NEWLINE) ||
854                                 (c == OUT && !(m->eflags&REG_NOTEOL)) ) {
855                         flagch = (flagch == BOL) ? BOLEOL : EOL;
856                         i += m->g->neol;
857                 }
858                 if (i != 0) {
859                         for (; i > 0; i--)
860                                 st = step(m->g, startst, stopst, st, flagch, st);
861                         SP("sboleol", st, c);
862                 }
863
864                 /* how about a word boundary? */
865                 if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) &&
866                                         (c != OUT && ISWORD(c)) ) {
867                         flagch = BOW;
868                 }
869                 if ( (lastc != OUT && ISWORD(lastc)) &&
870                                 (flagch == EOL || (c != OUT && !ISWORD(c))) ) {
871                         flagch = EOW;
872                 }
873                 if (flagch == BOW || flagch == EOW) {
874                         st = step(m->g, startst, stopst, st, flagch, st);
875                         SP("sboweow", st, c);
876                 }
877
878                 /* are we done? */
879                 if (ISSET(st, stopst))
880                         matchp = p;
881                 if (EQ(st, empty) || p == stop)
882                         break;          /* NOTE BREAK OUT */
883
884                 /* no, we must deal with this character */
885                 ASSIGN(tmp, st);
886                 ASSIGN(st, empty);
887                 assert(c != OUT);
888                 st = step(m->g, startst, stopst, tmp, c, st);
889                 SP("saft", st, c);
890                 assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st));
891                 p++;
892         }
893
894         return(matchp);
895 }
896
897
898 /*
899  - step - map set of states reachable before char to set reachable after
900  == static states step(struct re_guts *g, sopno start, sopno stop, \
901  ==     states bef, int ch, states aft);
902  == #define     BOL     (OUT+1)
903  == #define     EOL     (BOL+1)
904  == #define     BOLEOL  (BOL+2)
905  == #define     NOTHING (BOL+3)
906  == #define     BOW     (BOL+4)
907  == #define     EOW     (BOL+5)
908  == #define     CODEMAX (BOL+5)         // highest code used
909  == #define     NONCHAR(c)      ((c) > CHAR_MAX)
910  == #define     NNONCHAR        (CODEMAX-CHAR_MAX)
911  */
912 static states
913 step(struct re_guts *g,
914      sopno start,               /* start state within strip */
915      sopno stop,                /* state after stop state within strip */
916      states bef,                /* states reachable before */
917      int ch,                    /* character or NONCHAR code */
918      states aft)                /* states already known reachable after */
919 {
920         cset *cs;
921         sop s;
922         sopno pc;
923         onestate here;                  /* note, macros know this name */
924         sopno look;
925         int i;
926
927         for (pc = start, INIT(here, pc); pc != stop; pc++, INC(here)) {
928                 s = g->strip[pc];
929                 switch (OP(s)) {
930                 case OEND:
931                         assert(pc == stop-1);
932                         break;
933                 case OCHAR:
934                         /* only characters can match */
935                         assert(!NONCHAR(ch) || ch != (char)OPND(s));
936                         if (ch == (char)OPND(s))
937                                 FWD(aft, bef, 1);
938                         break;
939                 case OBOL:
940                         if (ch == BOL || ch == BOLEOL)
941                                 FWD(aft, bef, 1);
942                         break;
943                 case OEOL:
944                         if (ch == EOL || ch == BOLEOL)
945                                 FWD(aft, bef, 1);
946                         break;
947                 case OBOW:
948                         if (ch == BOW)
949                                 FWD(aft, bef, 1);
950                         break;
951                 case OEOW:
952                         if (ch == EOW)
953                                 FWD(aft, bef, 1);
954                         break;
955                 case OANY:
956                         if (!NONCHAR(ch))
957                                 FWD(aft, bef, 1);
958                         break;
959                 case OANYOF:
960                         cs = &g->sets[OPND(s)];
961                         if (!NONCHAR(ch) && CHIN(cs, ch))
962                                 FWD(aft, bef, 1);
963                         break;
964                 case OBACK_:            /* ignored here */
965                 case O_BACK:
966                         FWD(aft, aft, 1);
967                         break;
968                 case OPLUS_:            /* forward, this is just an empty */
969                         FWD(aft, aft, 1);
970                         break;
971                 case O_PLUS:            /* both forward and back */
972                         FWD(aft, aft, 1);
973                         i = ISSETBACK(aft, OPND(s));
974                         BACK(aft, aft, OPND(s));
975                         if (!i && ISSETBACK(aft, OPND(s))) {
976                                 /* oho, must reconsider loop body */
977                                 pc -= OPND(s) + 1;
978                                 INIT(here, pc);
979                         }
980                         break;
981                 case OQUEST_:           /* two branches, both forward */
982                         FWD(aft, aft, 1);
983                         FWD(aft, aft, OPND(s));
984                         break;
985                 case O_QUEST:           /* just an empty */
986                         FWD(aft, aft, 1);
987                         break;
988                 case OLPAREN:           /* not significant here */
989                 case ORPAREN:
990                         FWD(aft, aft, 1);
991                         break;
992                 case OCH_:              /* mark the first two branches */
993                         FWD(aft, aft, 1);
994                         assert(OP(g->strip[pc+OPND(s)]) == OOR2);
995                         FWD(aft, aft, OPND(s));
996                         break;
997                 case OOR1:              /* done a branch, find the O_CH */
998                         if (ISSTATEIN(aft, here)) {
999                                 for (look = 1;
1000                                                 OP(s = g->strip[pc+look]) != O_CH;
1001                                                 look += OPND(s))
1002                                         assert(OP(s) == OOR2);
1003                                 FWD(aft, aft, look);
1004                         }
1005                         break;
1006                 case OOR2:              /* propagate OCH_'s marking */
1007                         FWD(aft, aft, 1);
1008                         if (OP(g->strip[pc+OPND(s)]) != O_CH) {
1009                                 assert(OP(g->strip[pc+OPND(s)]) == OOR2);
1010                                 FWD(aft, aft, OPND(s));
1011                         }
1012                         break;
1013                 case O_CH:              /* just empty */
1014                         FWD(aft, aft, 1);
1015                         break;
1016                 default:                /* ooooops... */
1017                         assert(nope);
1018                         break;
1019                 }
1020         }
1021
1022         return(aft);
1023 }
1024
1025 #ifdef REDEBUG
1026 /*
1027  - print - print a set of states
1028  == #ifdef REDEBUG
1029  == static void print(struct match *m, char *caption, states st, \
1030  ==     int ch, FILE *d);
1031  == #endif
1032  */
1033 static void
1034 print(struct match *m, char *caption, states st, int ch, FILE *d)
1035 {
1036         struct re_guts *g = m->g;
1037         int i;
1038         int first = 1;
1039
1040         if (!(m->eflags&REG_TRACE))
1041                 return;
1042
1043         fprintf(d, "%s", caption);
1044         if (ch != '\0')
1045                 fprintf(d, " %s", pchar(ch));
1046         for (i = 0; i < g->nstates; i++)
1047                 if (ISSET(st, i)) {
1048                         fprintf(d, "%s%d", (first) ? "\t" : ", ", i);
1049                         first = 0;
1050                 }
1051         fprintf(d, "\n");
1052 }
1053
1054 /*
1055  - at - print current situation
1056  == #ifdef REDEBUG
1057  == static void at(struct match *m, char *title, char *start, char *stop, \
1058  ==                                             sopno startst, sopno stopst);
1059  == #endif
1060  */
1061 static void
1062 at(struct match *m, char *title, char *start, char *stop, sopno startst,
1063    sopno stopst)
1064 {
1065         if (!(m->eflags&REG_TRACE))
1066                 return;
1067
1068         printf("%s %s-", title, pchar(*start));
1069         printf("%s ", pchar(*stop));
1070         printf("%ld-%ld\n", (long)startst, (long)stopst);
1071 }
1072
1073 #ifndef PCHARDONE
1074 #define PCHARDONE       /* never again */
1075 /*
1076  - pchar - make a character printable
1077  == #ifdef REDEBUG
1078  == static char *pchar(int ch);
1079  == #endif
1080  *
1081  * Is this identical to regchar() over in debug.c?  Well, yes.  But a
1082  * duplicate here avoids having a debugging-capable regexec.o tied to
1083  * a matching debug.o, and this is convenient.  It all disappears in
1084  * the non-debug compilation anyway, so it doesn't matter much.
1085  */
1086 static char *                   /* -> representation */
1087 pchar(int ch)
1088 {
1089         static char pbuf[10];
1090
1091         if (isprint((uch)ch) || ch == ' ')
1092                 sprintf(pbuf, "%c", ch);
1093         else
1094                 sprintf(pbuf, "\\%o", ch);
1095         return(pbuf);
1096 }
1097 #endif
1098 #endif
1099
1100 #undef  matcher
1101 #undef  fast
1102 #undef  slow
1103 #undef  dissect
1104 #undef  backref
1105 #undef  step
1106 #undef  print
1107 #undef  at
1108 #undef  match