regexec.c 44.0 KB
Newer Older
1 2
/*
 * re_*exec and friends - match REs
3
 *
B
Bruce Momjian 已提交
4 5
 * Copyright (c) 1998, 1999 Henry Spencer.	All rights reserved.
 *
6 7 8
 * Development of this software was funded, in part, by Cray Research Inc.,
 * UUNET Communications Services Inc., Sun Microsystems Inc., and Scriptics
 * Corporation, none of whom are responsible for the results.  The author
B
Bruce Momjian 已提交
9 10
 * thanks all of them.
 *
11 12 13 14
 * Redistribution and use in source and binary forms -- with or without
 * modification -- are permitted for any purpose, provided that
 * redistributions in source form retain this entire copyright notice and
 * indicate the origin and nature of any modifications.
B
Bruce Momjian 已提交
15
 *
16 17
 * I'd appreciate being given credit for this package in the documentation
 * of software which uses it, but that is not a requirement.
B
Bruce Momjian 已提交
18
 *
19 20 21 22 23 24 25 26 27 28
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * HENRY SPENCER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * src/backend/regex/regexec.c
31 32 33
 *
 */

34 35 36 37 38
#include "regex/regguts.h"



/* lazy-DFA representation */
B
Bruce Momjian 已提交
39 40
struct arcp
{								/* "pointer" to an outarc */
41
	struct sset *ss;
B
Bruce Momjian 已提交
42
	color		co;
43 44
};

B
Bruce Momjian 已提交
45 46 47 48 49 50
struct sset
{								/* state set */
	unsigned   *states;			/* pointer to bitvector */
	unsigned	hash;			/* hash of bitvector */
#define  HASH(bv, nw)	 (((nw) == 1) ? *(bv) : hash(bv, nw))
#define  HIT(h,bv,ss,nw) ((ss)->hash == (h) && ((nw) == 1 || \
51
		memcmp(VS(bv), VS((ss)->states), (nw)*sizeof(unsigned)) == 0))
B
Bruce Momjian 已提交
52 53 54 55 56 57 58 59 60
	int			flags;
#define  STARTER	 01			/* the initial state set */
#define  POSTSTATE	 02			/* includes the goal state */
#define  LOCKED		 04			/* locked in cache */
#define  NOPROGRESS  010		/* zero-progress state set */
	struct arcp ins;			/* chain of inarcs pointing here */
	chr		   *lastseen;		/* last entered on arrival here */
	struct sset **outs;			/* outarc vector indexed by color */
	struct arcp *inchain;		/* chain-pointer vector for outarcs */
61 62
};

B
Bruce Momjian 已提交
63 64 65 66 67 68 69 70 71 72 73 74
struct dfa
{
	int			nssets;			/* size of cache */
	int			nssused;		/* how many entries occupied yet */
	int			nstates;		/* number of states */
	int			ncolors;		/* length of outarc and inchain vectors */
	int			wordsper;		/* length of state-set bitvectors */
	struct sset *ssets;			/* state-set cache */
	unsigned   *statesarea;		/* bitvector storage */
	unsigned   *work;			/* pointer to work area within statesarea */
	struct sset **outsarea;		/* outarc-vector storage */
	struct arcp *incarea;		/* inchain storage */
75 76
	struct cnfa *cnfa;
	struct colormap *cm;
B
Bruce Momjian 已提交
77
	chr		   *lastpost;		/* location of last cache-flushed success */
B
Bruce Momjian 已提交
78
	chr		   *lastnopr;		/* location of last cache-flushed NOPROGRESS */
B
Bruce Momjian 已提交
79 80 81
	struct sset *search;		/* replacement-search-pointer memory */
	int			cptsmalloced;	/* were the areas individually malloced? */
	char	   *mallocarea;		/* self, or master malloced area, or NULL */
82 83
};

B
Bruce Momjian 已提交
84
#define WORK	1				/* number of work bitvectors needed */
85 86

/* setup for non-malloc allocation for small cases */
B
Bruce Momjian 已提交
87 88 89 90 91 92 93 94 95
#define FEWSTATES	20			/* must be less than UBITS */
#define FEWCOLORS	15
struct smalldfa
{
	struct dfa	dfa;
	struct sset ssets[FEWSTATES * 2];
	unsigned	statesarea[FEWSTATES * 2 + WORK];
	struct sset *outsarea[FEWSTATES * 2 * FEWCOLORS];
	struct arcp incarea[FEWSTATES * 2 * FEWCOLORS];
96
};
B
Bruce Momjian 已提交
97 98

#define DOMALLOC	((struct smalldfa *)NULL)	/* force malloc */
99 100 101 102



/* internal variables, bundled for easy passing around */
B
Bruce Momjian 已提交
103 104 105
struct vars
{
	regex_t    *re;
106
	struct guts *g;
B
Bruce Momjian 已提交
107 108
	int			eflags;			/* copies of arguments */
	size_t		nmatch;
109 110
	regmatch_t *pmatch;
	rm_detail_t *details;
B
Bruce Momjian 已提交
111
	chr		   *start;			/* start of string */
112
	chr		   *search_start;	/* search start of string */
B
Bruce Momjian 已提交
113 114
	chr		   *stop;			/* just past end of string */
	int			err;			/* error code if any (0 none) */
115
	struct dfa **subdfas;		/* per-subre DFAs */
116 117 118 119
	struct smalldfa dfa1;
	struct smalldfa dfa2;
};

B
Bruce Momjian 已提交
120 121
#define VISERR(vv)	((vv)->err != 0)	/* have we seen an error yet? */
#define ISERR() VISERR(v)
122
#define VERR(vv,e)	((vv)->err = ((vv)->err ? (vv)->err : (e)))
B
Bruce Momjian 已提交
123
#define ERR(e)	VERR(v, e)		/* record an error */
B
Bruce Momjian 已提交
124
#define NOERR() {if (ISERR()) return v->err;}	/* if error seen, return it */
B
Bruce Momjian 已提交
125 126
#define OFF(p)	((p) - v->start)
#define LOFF(p) ((long)OFF(p))
127 128


129

130
/*
131 132 133
 * forward declarations
 */
/* === regexec.c === */
134
static struct dfa *getsubdfa(struct vars *, struct subre *);
B
Bruce Momjian 已提交
135 136 137
static int	find(struct vars *, struct cnfa *, struct colormap *);
static int	cfind(struct vars *, struct cnfa *, struct colormap *);
static int	cfindloop(struct vars *, struct cnfa *, struct colormap *, struct dfa *, struct dfa *, chr **);
138 139
static void zapallsubs(regmatch_t *, size_t);
static void zaptreesubs(struct vars *, struct subre *);
B
Bruce Momjian 已提交
140 141 142 143
static void subset(struct vars *, struct subre *, chr *, chr *);
static int	dissect(struct vars *, struct subre *, chr *, chr *);
static int	condissect(struct vars *, struct subre *, chr *, chr *);
static int	altdissect(struct vars *, struct subre *, chr *, chr *);
144 145
static int	iterdissect(struct vars *, struct subre *, chr *, chr *);
static int	reviterdissect(struct vars *, struct subre *, chr *, chr *);
B
Bruce Momjian 已提交
146 147 148 149 150
static int	cdissect(struct vars *, struct subre *, chr *, chr *);
static int	ccondissect(struct vars *, struct subre *, chr *, chr *);
static int	crevdissect(struct vars *, struct subre *, chr *, chr *);
static int	cbrdissect(struct vars *, struct subre *, chr *, chr *);
static int	caltdissect(struct vars *, struct subre *, chr *, chr *);
151 152
static int	citerdissect(struct vars *, struct subre *, chr *, chr *);
static int	creviterdissect(struct vars *, struct subre *, chr *, chr *);
B
Bruce Momjian 已提交
153

154
/* === rege_dfa.c === */
B
Bruce Momjian 已提交
155 156 157 158 159 160 161 162 163 164 165
static chr *longest(struct vars *, struct dfa *, chr *, chr *, int *);
static chr *shortest(struct vars *, struct dfa *, chr *, chr *, chr *, chr **, int *);
static chr *lastcold(struct vars *, struct dfa *);
static struct dfa *newdfa(struct vars *, struct cnfa *, struct colormap *, struct smalldfa *);
static void freedfa(struct dfa *);
static unsigned hash(unsigned *, int);
static struct sset *initialize(struct vars *, struct dfa *, chr *);
static struct sset *miss(struct vars *, struct dfa *, struct sset *, pcolor, chr *, chr *);
static int	lacon(struct vars *, struct cnfa *, chr *, pcolor);
static struct sset *getvacant(struct vars *, struct dfa *, chr *, chr *);
static struct sset *pickss(struct vars *, struct dfa *, chr *, chr *);
166 167 168 169 170 171 172


/*
 * pg_regexec - match regular expression
 */
int
pg_regexec(regex_t *re,
173
		   const chr *string,
174
		   size_t len,
175
		   size_t search_start,
176
		   rm_detail_t *details,
177 178 179 180 181 182
		   size_t nmatch,
		   regmatch_t pmatch[],
		   int flags)
{
	struct vars var;
	register struct vars *v = &var;
B
Bruce Momjian 已提交
183 184
	int			st;
	size_t		n;
185
	size_t		i;
B
Bruce Momjian 已提交
186 187 188 189 190
	int			backref;

#define  LOCALMAT	 20
	regmatch_t	mat[LOCALMAT];

191 192 193
#define  LOCALDFAS	 40
	struct dfa *subdfas[LOCALDFAS];

194 195 196 197 198 199
	/* sanity checks */
	if (re == NULL || string == NULL || re->re_magic != REMAGIC)
		return REG_INVARG;
	if (re->re_csize != sizeof(chr))
		return REG_MIXED;

200 201 202
	/* Initialize locale-dependent support */
	pg_set_regex_collation(re->re_collation);

203 204
	/* setup */
	v->re = re;
B
Bruce Momjian 已提交
205 206
	v->g = (struct guts *) re->re_guts;
	if ((v->g->cflags & REG_EXPECT) && details == NULL)
207
		return REG_INVARG;
B
Bruce Momjian 已提交
208
	if (v->g->info & REG_UIMPOSSIBLE)
209
		return REG_NOMATCH;
B
Bruce Momjian 已提交
210
	backref = (v->g->info & REG_UBACKREF) ? 1 : 0;
211
	v->eflags = flags;
B
Bruce Momjian 已提交
212 213
	if (v->g->cflags & REG_NOSUB)
		nmatch = 0;				/* override client */
214
	v->nmatch = nmatch;
B
Bruce Momjian 已提交
215 216
	if (backref)
	{
217 218 219 220
		/* need work area */
		if (v->g->nsub + 1 <= LOCALMAT)
			v->pmatch = mat;
		else
B
Bruce Momjian 已提交
221 222
			v->pmatch = (regmatch_t *) MALLOC((v->g->nsub + 1) *
											  sizeof(regmatch_t));
223 224 225
		if (v->pmatch == NULL)
			return REG_ESPACE;
		v->nmatch = v->g->nsub + 1;
B
Bruce Momjian 已提交
226 227
	}
	else
228 229
		v->pmatch = pmatch;
	v->details = details;
B
Bruce Momjian 已提交
230
	v->start = (chr *) string;
231
	v->search_start = (chr *) string + search_start;
B
Bruce Momjian 已提交
232
	v->stop = (chr *) string + len;
233
	v->err = 0;
234 235 236 237 238 239 240 241 242 243 244 245 246 247
	assert(v->g->ntree >= 0);
	n = (size_t) v->g->ntree;
	if (n <= LOCALDFAS)
		v->subdfas = subdfas;
	else
		v->subdfas = (struct dfa **) MALLOC(n * sizeof(struct dfa *));
	if (v->subdfas == NULL)
	{
		if (v->pmatch != pmatch && v->pmatch != mat)
			FREE(v->pmatch);
		return REG_ESPACE;
	}
	for (i = 0; i < n; i++)
		v->subdfas[i] = NULL;
248 249 250 251 252 253 254 255 256

	/* do it */
	assert(v->g->tree != NULL);
	if (backref)
		st = cfind(v, &v->g->tree->cnfa, &v->g->cmap);
	else
		st = find(v, &v->g->tree->cnfa, &v->g->cmap);

	/* copy (portion of) match vector over if necessary */
B
Bruce Momjian 已提交
257 258
	if (st == REG_OKAY && v->pmatch != pmatch && nmatch > 0)
	{
259
		zapallsubs(pmatch, nmatch);
260
		n = (nmatch < v->nmatch) ? nmatch : v->nmatch;
B
Bruce Momjian 已提交
261
		memcpy(VS(pmatch), VS(v->pmatch), n * sizeof(regmatch_t));
262 263 264 265 266
	}

	/* clean up */
	if (v->pmatch != pmatch && v->pmatch != mat)
		FREE(v->pmatch);
267 268 269 270 271 272 273 274
	for (i = 0; i < n; i++)
	{
		if (v->subdfas[i] != NULL)
			freedfa(v->subdfas[i]);
	}
	if (v->subdfas != subdfas)
		FREE(v->subdfas);

275 276 277
	return st;
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
/*
 * getsubdfa - create or re-fetch the DFA for a subre node
 *
 * We only need to create the DFA once per overall regex execution.
 * The DFA will be freed by the cleanup step in pg_regexec().
 */
static struct dfa *
getsubdfa(struct vars * v,
		  struct subre * t)
{
	if (v->subdfas[t->id] == NULL)
	{
		v->subdfas[t->id] = newdfa(v, &t->cnfa, &v->g->cmap, DOMALLOC);
		if (ISERR())
			return NULL;
	}
	return v->subdfas[t->id];
}

297 298 299 300
/*
 * find - find a match for the main NFA (no-complications case)
 */
static int
B
Bruce Momjian 已提交
301 302 303
find(struct vars * v,
	 struct cnfa * cnfa,
	 struct colormap * cm)
304 305 306
{
	struct dfa *s;
	struct dfa *d;
B
Bruce Momjian 已提交
307 308 309
	chr		   *begin;
	chr		   *end = NULL;
	chr		   *cold;
B
Bruce Momjian 已提交
310
	chr		   *open;			/* open and close of range of possible starts */
B
Bruce Momjian 已提交
311 312 313
	chr		   *close;
	int			hitend;
	int			shorter = (v->g->tree->flags & SHORTER) ? 1 : 0;
314 315 316 317 318 319 320

	/* first, a shot with the search RE */
	s = newdfa(v, &v->g->search, cm, &v->dfa1);
	assert(!(ISERR() && s != NULL));
	NOERR();
	MDEBUG(("\nsearch at %ld\n", LOFF(v->start)));
	cold = NULL;
321 322
	close = shortest(v, s, v->search_start, v->search_start, v->stop,
					 &cold, (int *) NULL);
323 324
	freedfa(s);
	NOERR();
B
Bruce Momjian 已提交
325 326
	if (v->g->cflags & REG_EXPECT)
	{
327 328 329 330 331
		assert(v->details != NULL);
		if (cold != NULL)
			v->details->rm_extend.rm_so = OFF(cold);
		else
			v->details->rm_extend.rm_so = OFF(v->stop);
B
Bruce Momjian 已提交
332
		v->details->rm_extend.rm_eo = OFF(v->stop);		/* unknown */
333
	}
B
Bruce Momjian 已提交
334
	if (close == NULL)			/* not found */
335
		return REG_NOMATCH;
B
Bruce Momjian 已提交
336
	if (v->nmatch == 0)			/* found, don't need exact location */
337 338 339 340 341 342 343 344 345 346
		return REG_OKAY;

	/* find starting point and match */
	assert(cold != NULL);
	open = cold;
	cold = NULL;
	MDEBUG(("between %ld and %ld\n", LOFF(open), LOFF(close)));
	d = newdfa(v, cnfa, cm, &v->dfa1);
	assert(!(ISERR() && d != NULL));
	NOERR();
B
Bruce Momjian 已提交
347 348
	for (begin = open; begin <= close; begin++)
	{
349 350 351
		MDEBUG(("\nfind trying at %ld\n", LOFF(begin)));
		if (shorter)
			end = shortest(v, d, begin, begin, v->stop,
B
Bruce Momjian 已提交
352
						   (chr **) NULL, &hitend);
353 354 355 356 357 358
		else
			end = longest(v, d, begin, v->stop, &hitend);
		NOERR();
		if (hitend && cold == NULL)
			cold = begin;
		if (end != NULL)
B
Bruce Momjian 已提交
359
			break;				/* NOTE BREAK OUT */
360 361 362 363 364 365 366 367
	}
	assert(end != NULL);		/* search RE succeeded so loop should */
	freedfa(d);

	/* and pin down details */
	assert(v->nmatch > 0);
	v->pmatch[0].rm_so = OFF(begin);
	v->pmatch[0].rm_eo = OFF(end);
B
Bruce Momjian 已提交
368 369
	if (v->g->cflags & REG_EXPECT)
	{
370 371 372 373
		if (cold != NULL)
			v->details->rm_extend.rm_so = OFF(cold);
		else
			v->details->rm_extend.rm_so = OFF(v->stop);
B
Bruce Momjian 已提交
374
		v->details->rm_extend.rm_eo = OFF(v->stop);		/* unknown */
375
	}
B
Bruce Momjian 已提交
376
	if (v->nmatch == 1)			/* no need for submatches */
377 378 379
		return REG_OKAY;

	/* submatches */
380
	zapallsubs(v->pmatch, v->nmatch);
381 382 383 384 385 386 387
	return dissect(v, v->g->tree, begin, end);
}

/*
 * cfind - find a match for the main NFA (with complications)
 */
static int
B
Bruce Momjian 已提交
388 389 390
cfind(struct vars * v,
	  struct cnfa * cnfa,
	  struct colormap * cm)
391 392 393
{
	struct dfa *s;
	struct dfa *d;
B
Bruce Momjian 已提交
394 395
	chr		   *cold;
	int			ret;
396 397 398 399

	s = newdfa(v, &v->g->search, cm, &v->dfa1);
	NOERR();
	d = newdfa(v, cnfa, cm, &v->dfa2);
B
Bruce Momjian 已提交
400 401
	if (ISERR())
	{
402 403 404 405 406 407 408 409 410 411
		assert(d == NULL);
		freedfa(s);
		return v->err;
	}

	ret = cfindloop(v, cnfa, cm, d, s, &cold);

	freedfa(d);
	freedfa(s);
	NOERR();
B
Bruce Momjian 已提交
412 413
	if (v->g->cflags & REG_EXPECT)
	{
414 415 416 417 418
		assert(v->details != NULL);
		if (cold != NULL)
			v->details->rm_extend.rm_so = OFF(cold);
		else
			v->details->rm_extend.rm_so = OFF(v->stop);
B
Bruce Momjian 已提交
419
		v->details->rm_extend.rm_eo = OFF(v->stop);		/* unknown */
420 421 422 423 424 425 426 427
	}
	return ret;
}

/*
 * cfindloop - the heart of cfind
 */
static int
B
Bruce Momjian 已提交
428 429 430 431 432
cfindloop(struct vars * v,
		  struct cnfa * cnfa,
		  struct colormap * cm,
		  struct dfa * d,
		  struct dfa * s,
433
		  chr **coldp)			/* where to put coldstart pointer */
434
{
B
Bruce Momjian 已提交
435 436 437
	chr		   *begin;
	chr		   *end;
	chr		   *cold;
B
Bruce Momjian 已提交
438
	chr		   *open;			/* open and close of range of possible starts */
B
Bruce Momjian 已提交
439 440 441 442 443 444
	chr		   *close;
	chr		   *estart;
	chr		   *estop;
	int			er;
	int			shorter = v->g->tree->flags & SHORTER;
	int			hitend;
445 446 447

	assert(d != NULL && s != NULL);
	cold = NULL;
448
	close = v->search_start;
B
Bruce Momjian 已提交
449 450
	do
	{
451
		MDEBUG(("\ncsearch at %ld\n", LOFF(close)));
B
Bruce Momjian 已提交
452
		close = shortest(v, s, close, close, v->stop, &cold, (int *) NULL);
453 454 455 456 457 458
		if (close == NULL)
			break;				/* NOTE BREAK */
		assert(cold != NULL);
		open = cold;
		cold = NULL;
		MDEBUG(("cbetween %ld and %ld\n", LOFF(open), LOFF(close)));
B
Bruce Momjian 已提交
459 460
		for (begin = open; begin <= close; begin++)
		{
461 462 463
			MDEBUG(("\ncfind trying at %ld\n", LOFF(begin)));
			estart = begin;
			estop = v->stop;
B
Bruce Momjian 已提交
464 465
			for (;;)
			{
466 467
				if (shorter)
					end = shortest(v, d, begin, estart,
B
Bruce Momjian 已提交
468
								   estop, (chr **) NULL, &hitend);
469 470
				else
					end = longest(v, d, begin, estop,
B
Bruce Momjian 已提交
471
								  &hitend);
472 473 474 475 476
				if (hitend && cold == NULL)
					cold = begin;
				if (end == NULL)
					break;		/* NOTE BREAK OUT */
				MDEBUG(("tentative end %ld\n", LOFF(end)));
477
				zapallsubs(v->pmatch, v->nmatch);
478
				er = cdissect(v, v->g->tree, begin, end);
B
Bruce Momjian 已提交
479 480 481 482
				if (er == REG_OKAY)
				{
					if (v->nmatch > 0)
					{
483 484 485 486 487 488
						v->pmatch[0].rm_so = OFF(begin);
						v->pmatch[0].rm_eo = OFF(end);
					}
					*coldp = cold;
					return REG_OKAY;
				}
B
Bruce Momjian 已提交
489 490
				if (er != REG_NOMATCH)
				{
491
					ERR(er);
492
					*coldp = cold;
493 494
					return er;
				}
B
Bruce Momjian 已提交
495 496
				if ((shorter) ? end == estop : end == begin)
				{
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
					/* no point in trying again */
					*coldp = cold;
					return REG_NOMATCH;
				}
				/* go around and try again */
				if (shorter)
					estart = end + 1;
				else
					estop = end - 1;
			}
		}
	} while (close < v->stop);

	*coldp = cold;
	return REG_NOMATCH;
}

/*
515
 * zapallsubs - initialize all subexpression matches to "no match"
516 517
 */
static void
518 519
zapallsubs(regmatch_t *p,
		   size_t n)
520
{
B
Bruce Momjian 已提交
521
	size_t		i;
522

B
Bruce Momjian 已提交
523 524
	for (i = n - 1; i > 0; i--)
	{
525 526 527 528 529 530
		p[i].rm_so = -1;
		p[i].rm_eo = -1;
	}
}

/*
531
 * zaptreesubs - initialize subexpressions within subtree to "no match"
532 533
 */
static void
534 535
zaptreesubs(struct vars * v,
			struct subre * t)
536
{
B
Bruce Momjian 已提交
537 538
	if (t->op == '(')
	{
539 540 541 542 543 544
		assert(t->subno > 0);
		v->pmatch[t->subno].rm_so = -1;
		v->pmatch[t->subno].rm_eo = -1;
	}

	if (t->left != NULL)
545
		zaptreesubs(v, t->left);
546
	if (t->right != NULL)
547
		zaptreesubs(v, t->right);
548 549 550 551 552 553
}

/*
 * subset - set any subexpression relevant to a successful subre
 */
static void
B
Bruce Momjian 已提交
554 555
subset(struct vars * v,
	   struct subre * sub,
556 557
	   chr *begin,
	   chr *end)
558
{
B
Bruce Momjian 已提交
559
	int			n = sub->subno;
560 561

	assert(n > 0);
B
Bruce Momjian 已提交
562
	if ((size_t) n >= v->nmatch)
563 564 565 566 567 568 569 570 571 572
		return;

	MDEBUG(("setting %d\n", n));
	v->pmatch[n].rm_so = OFF(begin);
	v->pmatch[n].rm_eo = OFF(end);
}

/*
 * dissect - determine subexpression matches (uncomplicated case)
 */
B
Bruce Momjian 已提交
573 574 575
static int						/* regexec return code */
dissect(struct vars * v,
		struct subre * t,
576 577
		chr *begin,				/* beginning of relevant substring */
		chr *end)				/* end of same */
578 579 580 581
{
	assert(t != NULL);
	MDEBUG(("dissect %ld-%ld\n", LOFF(begin), LOFF(end)));

B
Bruce Momjian 已提交
582 583 584 585 586 587 588 589 590 591
	switch (t->op)
	{
		case '=':				/* terminal node */
			assert(t->left == NULL && t->right == NULL);
			return REG_OKAY;	/* no action, parent did the work */
		case 'b':				/* back ref -- shouldn't be calling us! */
			return REG_ASSERT;
		case '.':				/* concatenation */
			assert(t->left != NULL && t->right != NULL);
			return condissect(v, t, begin, end);
592 593 594 595 596 597
		case '|':				/* alternation */
			assert(t->left != NULL);
			return altdissect(v, t, begin, end);
		case '*':				/* iteration */
			assert(t->left != NULL);
			return iterdissect(v, t, begin, end);
B
Bruce Momjian 已提交
598 599 600 601 602 603 604
		case '(':				/* capturing */
			assert(t->left != NULL && t->right == NULL);
			assert(t->subno > 0);
			subset(v, t, begin, end);
			return dissect(v, t->left, begin, end);
		default:
			return REG_ASSERT;
605 606 607 608 609
	}
}

/*
 * condissect - determine concatenation subexpression matches (uncomplicated)
610
 */
B
Bruce Momjian 已提交
611 612 613
static int						/* regexec return code */
condissect(struct vars * v,
		   struct subre * t,
614 615
		   chr *begin,			/* beginning of relevant substring */
		   chr *end)			/* end of same */
616
{
617 618
	struct dfa *d;
	struct dfa *d2;
B
Bruce Momjian 已提交
619 620 621 622
	chr		   *mid;
	int			i;
	int			shorter = (t->left->flags & SHORTER) ? 1 : 0;
	chr		   *stop = (shorter) ? end : begin;
623 624 625 626 627

	assert(t->op == '.');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(t->right != NULL && t->right->cnfa.nstates > 0);

628 629 630
	d = getsubdfa(v, t->left);
	NOERR();
	d2 = getsubdfa(v, t->right);
631 632 633 634
	NOERR();

	/* pick a tentative midpoint */
	if (shorter)
B
Bruce Momjian 已提交
635 636
		mid = shortest(v, d, begin, begin, end, (chr **) NULL,
					   (int *) NULL);
637
	else
B
Bruce Momjian 已提交
638 639
		mid = longest(v, d, begin, end, (int *) NULL);
	if (mid == NULL)
640 641 642 643
		return REG_ASSERT;
	MDEBUG(("tentative midpoint %ld\n", LOFF(mid)));

	/* iterate until satisfaction or failure */
B
Bruce Momjian 已提交
644 645
	while (longest(v, d2, mid, end, (int *) NULL) != end)
	{
646
		/* that midpoint didn't work, find a new one */
B
Bruce Momjian 已提交
647 648
		if (mid == stop)
		{
649 650 651 652 653
			/* all possibilities exhausted! */
			MDEBUG(("no midpoint!\n"));
			return REG_ASSERT;
		}
		if (shorter)
B
Bruce Momjian 已提交
654 655
			mid = shortest(v, d, begin, mid + 1, end, (chr **) NULL,
						   (int *) NULL);
656
		else
B
Bruce Momjian 已提交
657 658 659
			mid = longest(v, d, begin, mid - 1, (int *) NULL);
		if (mid == NULL)
		{
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
			/* failed to find a new one! */
			MDEBUG(("failed midpoint!\n"));
			return REG_ASSERT;
		}
		MDEBUG(("new midpoint %ld\n", LOFF(mid)));
	}

	/* satisfaction */
	MDEBUG(("successful\n"));
	i = dissect(v, t->left, begin, mid);
	if (i != REG_OKAY)
		return i;
	return dissect(v, t->right, mid, end);
}

/*
 * altdissect - determine alternative subexpression matches (uncomplicated)
 */
B
Bruce Momjian 已提交
678 679 680
static int						/* regexec return code */
altdissect(struct vars * v,
		   struct subre * t,
681 682
		   chr *begin,			/* beginning of relevant substring */
		   chr *end)			/* end of same */
683 684
{
	struct dfa *d;
B
Bruce Momjian 已提交
685
	int			i;
686 687 688 689

	assert(t != NULL);
	assert(t->op == '|');

B
Bruce Momjian 已提交
690 691
	for (i = 0; t != NULL; t = t->right, i++)
	{
692 693
		MDEBUG(("trying %dth\n", i));
		assert(t->left != NULL && t->left->cnfa.nstates > 0);
694 695
		d = getsubdfa(v, t->left);
		NOERR();
B
Bruce Momjian 已提交
696 697
		if (longest(v, d, begin, end, (int *) NULL) == end)
		{
698 699 700 701
			MDEBUG(("success\n"));
			return dissect(v, t->left, begin, end);
		}
	}
B
Bruce Momjian 已提交
702
	return REG_ASSERT;			/* none of them matched?!? */
703 704
}

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
/*
 * iterdissect - iteration subexpression matches (uncomplicated)
 */
static int						/* regexec return code */
iterdissect(struct vars * v,
			struct subre * t,
			chr *begin,			/* beginning of relevant substring */
			chr *end)			/* end of same */
{
	struct dfa *d;
	chr		  **endpts;
	chr		   *limit;
	int			min_matches;
	size_t		max_matches;
	int			nverified;
	int			k;
	int			i;
	int			er;

	assert(t->op == '*');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(begin <= end);

	if (t->left->flags & SHORTER)		/* reverse scan */
		return reviterdissect(v, t, begin, end);

	/*
	 * If zero matches are allowed, and target string is empty, just declare
	 * victory.  OTOH, if target string isn't empty, zero matches can't work
	 * so we pretend the min is 1.
	 */
	min_matches = t->min;
	if (min_matches <= 0)
	{
		if (begin == end)
			return REG_OKAY;
		min_matches = 1;
	}

	/*
	 * We need workspace to track the endpoints of each sub-match.  Normally
	 * we consider only nonzero-length sub-matches, so there can be at most
	 * end-begin of them.  However, if min is larger than that, we will also
	 * consider zero-length sub-matches in order to find enough matches.
	 *
	 * For convenience, endpts[0] contains the "begin" pointer and we store
	 * sub-match endpoints in endpts[1..max_matches].
	 */
	max_matches = end - begin;
	if (max_matches > t->max && t->max != INFINITY)
		max_matches = t->max;
	if (max_matches < min_matches)
		max_matches = min_matches;
	endpts = (chr **) MALLOC((max_matches + 1) * sizeof(chr *));
	if (endpts == NULL)
		return REG_ESPACE;
	endpts[0] = begin;

763
	d = getsubdfa(v, t->left);
764 765 766 767 768
	if (ISERR())
	{
		FREE(endpts);
		return v->err;
	}
769
	MDEBUG(("iter %d\n", t->id));
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

	/*
	 * Our strategy is to first find a set of sub-match endpoints that are
	 * valid according to the child node's DFA, and then recursively dissect
	 * each sub-match to confirm validity.  If any validity check fails,
	 * backtrack the last sub-match and try again.  And, when we next try for
	 * a validity check, we need not recheck any successfully verified
	 * sub-matches that we didn't move the endpoints of.  nverified remembers
	 * how many sub-matches are currently known okay.
	 */

	/* initialize to consider first sub-match */
	nverified = 0;
	k = 1;
	limit = end;

	/* iterate until satisfaction or failure */
	while (k > 0)
	{
		/* try to find an endpoint for the k'th sub-match */
		endpts[k] = longest(v, d, endpts[k - 1], limit, (int *) NULL);
		if (endpts[k] == NULL)
		{
			/* no match possible, so see if we can shorten previous one */
			k--;
			goto backtrack;
		}
		MDEBUG(("%d: working endpoint %d: %ld\n",
798
				t->id, k, LOFF(endpts[k])));
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832

		/* k'th sub-match can no longer be considered verified */
		if (nverified >= k)
			nverified = k - 1;

		if (endpts[k] != end)
		{
			/* haven't reached end yet, try another iteration if allowed */
			if (k >= max_matches)
			{
				/* must try to shorten some previous match */
				k--;
				goto backtrack;
			}

			/* reject zero-length match unless necessary to achieve min */
			if (endpts[k] == endpts[k - 1] &&
				(k >= min_matches || min_matches - k < end - endpts[k]))
				goto backtrack;

			k++;
			limit = end;
			continue;
		}

		/*
		 * We've identified a way to divide the string into k sub-matches
		 * that works so far as the child DFA can tell.  If k is an allowed
		 * number of matches, start the slow part: recurse to verify each
		 * sub-match.  We always have k <= max_matches, needn't check that.
		 */
		if (k < min_matches)
			goto backtrack;

833
		MDEBUG(("%d: verifying %d..%d\n", t->id, nverified + 1, k));
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

		for (i = nverified + 1; i <= k; i++)
		{
			er = dissect(v, t->left, endpts[i - 1], endpts[i]);
			if (er == REG_OKAY)
			{
				nverified = i;
				continue;
			}
			if (er == REG_NOMATCH)
				break;
			/* oops, something failed */
			FREE(endpts);
			return er;
		}

		if (i > k)
		{
			/* satisfaction */
853
			MDEBUG(("%d successful\n", t->id));
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
			FREE(endpts);
			return REG_OKAY;
		}

		/* match failed to verify, so backtrack */

backtrack:
		/*
		 * Must consider shorter versions of the current sub-match.  However,
		 * we'll only ask for a zero-length match if necessary.
		 */
		while (k > 0)
		{
			chr	   *prev_end = endpts[k - 1];

			if (endpts[k] > prev_end)
			{
				limit = endpts[k] - 1;
				if (limit > prev_end ||
					(k < min_matches && min_matches - k >= end - prev_end))
				{
					/* break out of backtrack loop, continue the outer one */
					break;
				}
			}
			/* can't shorten k'th sub-match any more, consider previous one */
			k--;
		}
	}

	/* all possibilities exhausted - shouldn't happen in uncomplicated mode */
885
	MDEBUG(("%d failed\n", t->id));
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
	FREE(endpts);
	return REG_ASSERT;
}

/*
 * reviterdissect - shortest-first iteration subexpression matches
 */
static int						/* regexec return code */
reviterdissect(struct vars * v,
			   struct subre * t,
			   chr *begin,		/* beginning of relevant substring */
			   chr *end)		/* end of same */
{
	struct dfa *d;
	chr		  **endpts;
	chr		   *limit;
	int			min_matches;
	size_t		max_matches;
	int			nverified;
	int			k;
	int			i;
	int			er;

	assert(t->op == '*');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(t->left->flags & SHORTER);
	assert(begin <= end);

	/*
	 * If zero matches are allowed, and target string is empty, just declare
	 * victory.  OTOH, if target string isn't empty, zero matches can't work
	 * so we pretend the min is 1.
	 */
	min_matches = t->min;
	if (min_matches <= 0)
	{
		if (begin == end)
			return REG_OKAY;
		min_matches = 1;
	}

	/*
	 * We need workspace to track the endpoints of each sub-match.  Normally
	 * we consider only nonzero-length sub-matches, so there can be at most
	 * end-begin of them.  However, if min is larger than that, we will also
	 * consider zero-length sub-matches in order to find enough matches.
	 *
	 * For convenience, endpts[0] contains the "begin" pointer and we store
	 * sub-match endpoints in endpts[1..max_matches].
	 */
	max_matches = end - begin;
	if (max_matches > t->max && t->max != INFINITY)
		max_matches = t->max;
	if (max_matches < min_matches)
		max_matches = min_matches;
	endpts = (chr **) MALLOC((max_matches + 1) * sizeof(chr *));
	if (endpts == NULL)
		return REG_ESPACE;
	endpts[0] = begin;

946
	d = getsubdfa(v, t->left);
947 948 949 950 951
	if (ISERR())
	{
		FREE(endpts);
		return v->err;
	}
952
	MDEBUG(("reviter %d\n", t->id));
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987

	/*
	 * Our strategy is to first find a set of sub-match endpoints that are
	 * valid according to the child node's DFA, and then recursively dissect
	 * each sub-match to confirm validity.  If any validity check fails,
	 * backtrack the last sub-match and try again.  And, when we next try for
	 * a validity check, we need not recheck any successfully verified
	 * sub-matches that we didn't move the endpoints of.  nverified remembers
	 * how many sub-matches are currently known okay.
	 */

	/* initialize to consider first sub-match */
	nverified = 0;
	k = 1;
	limit = begin;

	/* iterate until satisfaction or failure */
	while (k > 0)
	{
		/* disallow zero-length match unless necessary to achieve min */
		if (limit == endpts[k - 1] &&
			limit != end &&
			(k >= min_matches || min_matches - k < end - limit))
			limit++;

		/* try to find an endpoint for the k'th sub-match */
		endpts[k] = shortest(v, d, endpts[k - 1], limit, end,
							 (chr **) NULL, (int *) NULL);
		if (endpts[k] == NULL)
		{
			/* no match possible, so see if we can lengthen previous one */
			k--;
			goto backtrack;
		}
		MDEBUG(("%d: working endpoint %d: %ld\n",
988
				t->id, k, LOFF(endpts[k])));
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

		/* k'th sub-match can no longer be considered verified */
		if (nverified >= k)
			nverified = k - 1;

		if (endpts[k] != end)
		{
			/* haven't reached end yet, try another iteration if allowed */
			if (k >= max_matches)
			{
				/* must try to lengthen some previous match */
				k--;
				goto backtrack;
			}

			k++;
			limit = endpts[k - 1];
			continue;
		}

		/*
		 * We've identified a way to divide the string into k sub-matches
		 * that works so far as the child DFA can tell.  If k is an allowed
		 * number of matches, start the slow part: recurse to verify each
		 * sub-match.  We always have k <= max_matches, needn't check that.
		 */
		if (k < min_matches)
			goto backtrack;

1018
		MDEBUG(("%d: verifying %d..%d\n", t->id, nverified + 1, k));
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

		for (i = nverified + 1; i <= k; i++)
		{
			er = dissect(v, t->left, endpts[i - 1], endpts[i]);
			if (er == REG_OKAY)
			{
				nverified = i;
				continue;
			}
			if (er == REG_NOMATCH)
				break;
			/* oops, something failed */
			FREE(endpts);
			return er;
		}

		if (i > k)
		{
			/* satisfaction */
1038
			MDEBUG(("%d successful\n", t->id));
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
			FREE(endpts);
			return REG_OKAY;
		}

		/* match failed to verify, so backtrack */

backtrack:
		/*
		 * Must consider longer versions of the current sub-match.
		 */
		while (k > 0)
		{
			if (endpts[k] < end)
			{
				limit = endpts[k] + 1;
				/* break out of backtrack loop, continue the outer one */
				break;
			}
			/* can't lengthen k'th sub-match any more, consider previous one */
			k--;
		}
	}

	/* all possibilities exhausted - shouldn't happen in uncomplicated mode */
1063
	MDEBUG(("%d failed\n", t->id));
1064 1065 1066 1067
	FREE(endpts);
	return REG_ASSERT;
}

1068 1069 1070
/*
 * cdissect - determine subexpression matches (with complications)
 */
B
Bruce Momjian 已提交
1071 1072 1073
static int						/* regexec return code */
cdissect(struct vars * v,
		 struct subre * t,
1074 1075
		 chr *begin,			/* beginning of relevant substring */
		 chr *end)				/* end of same */
1076
{
T
Tom Lane 已提交
1077 1078
	int			er;

1079 1080 1081
	assert(t != NULL);
	MDEBUG(("cdissect %ld-%ld %c\n", LOFF(begin), LOFF(end), t->op));

B
Bruce Momjian 已提交
1082 1083 1084 1085 1086
	switch (t->op)
	{
		case '=':				/* terminal node */
			assert(t->left == NULL && t->right == NULL);
			return REG_OKAY;	/* no action, parent did the work */
1087
		case 'b':				/* back reference */
B
Bruce Momjian 已提交
1088 1089 1090 1091 1092
			assert(t->left == NULL && t->right == NULL);
			return cbrdissect(v, t, begin, end);
		case '.':				/* concatenation */
			assert(t->left != NULL && t->right != NULL);
			return ccondissect(v, t, begin, end);
1093 1094 1095 1096 1097 1098
		case '|':				/* alternation */
			assert(t->left != NULL);
			return caltdissect(v, t, begin, end);
		case '*':				/* iteration */
			assert(t->left != NULL);
			return citerdissect(v, t, begin, end);
B
Bruce Momjian 已提交
1099 1100
		case '(':				/* capturing */
			assert(t->left != NULL && t->right == NULL);
T
Tom Lane 已提交
1101 1102 1103 1104 1105
			assert(t->subno > 0);
			er = cdissect(v, t->left, begin, end);
			if (er == REG_OKAY)
				subset(v, t, begin, end);
			return er;
B
Bruce Momjian 已提交
1106 1107
		default:
			return REG_ASSERT;
1108 1109 1110 1111 1112 1113
	}
}

/*
 * ccondissect - concatenation subexpression matches (with complications)
 */
B
Bruce Momjian 已提交
1114 1115 1116
static int						/* regexec return code */
ccondissect(struct vars * v,
			struct subre * t,
1117 1118
			chr *begin,			/* beginning of relevant substring */
			chr *end)			/* end of same */
1119 1120 1121
{
	struct dfa *d;
	struct dfa *d2;
B
Bruce Momjian 已提交
1122 1123
	chr		   *mid;
	int			er;
1124 1125 1126 1127 1128

	assert(t->op == '.');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(t->right != NULL && t->right->cnfa.nstates > 0);

B
Bruce Momjian 已提交
1129
	if (t->left->flags & SHORTER)		/* reverse scan */
1130 1131
		return crevdissect(v, t, begin, end);

1132 1133 1134 1135
	d = getsubdfa(v, t->left);
	NOERR();
	d2 = getsubdfa(v, t->right);
	NOERR();
1136
	MDEBUG(("cconcat %d\n", t->id));
1137 1138

	/* pick a tentative midpoint */
1139 1140 1141 1142
	mid = longest(v, d, begin, end, (int *) NULL);
	if (mid == NULL)
		return REG_NOMATCH;
	MDEBUG(("tentative midpoint %ld\n", LOFF(mid)));
1143 1144

	/* iterate until satisfaction or failure */
B
Bruce Momjian 已提交
1145 1146
	for (;;)
	{
1147
		/* try this midpoint on for size */
1148
		if (longest(v, d2, mid, end, (int *) NULL) == end)
B
Bruce Momjian 已提交
1149
		{
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
			er = cdissect(v, t->left, begin, mid);
			if (er == REG_OKAY)
			{
				er = cdissect(v, t->right, mid, end);
				if (er == REG_OKAY)
				{
					/* satisfaction */
					MDEBUG(("successful\n"));
					return REG_OKAY;
				}
			}
			if (er != REG_OKAY && er != REG_NOMATCH)
				return er;
1163 1164 1165
		}

		/* that midpoint didn't work, find a new one */
B
Bruce Momjian 已提交
1166 1167
		if (mid == begin)
		{
1168
			/* all possibilities exhausted */
1169
			MDEBUG(("%d no midpoint\n", t->id));
1170 1171
			return REG_NOMATCH;
		}
B
Bruce Momjian 已提交
1172 1173 1174
		mid = longest(v, d, begin, mid - 1, (int *) NULL);
		if (mid == NULL)
		{
1175
			/* failed to find a new one */
1176
			MDEBUG(("%d failed midpoint\n", t->id));
1177 1178
			return REG_NOMATCH;
		}
1179 1180 1181
		MDEBUG(("%d: new midpoint %ld\n", t->id, LOFF(mid)));
		zaptreesubs(v, t->left);
		zaptreesubs(v, t->right);
1182 1183
	}

1184 1185
	/* can't get here */
	return REG_ASSERT;
1186
}
1187 1188

/*
1189
 * crevdissect - shortest-first concatenation subexpression matches
1190
 */
B
Bruce Momjian 已提交
1191 1192 1193
static int						/* regexec return code */
crevdissect(struct vars * v,
			struct subre * t,
1194 1195
			chr *begin,			/* beginning of relevant substring */
			chr *end)			/* end of same */
1196 1197 1198
{
	struct dfa *d;
	struct dfa *d2;
B
Bruce Momjian 已提交
1199 1200
	chr		   *mid;
	int			er;
1201 1202 1203 1204

	assert(t->op == '.');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(t->right != NULL && t->right->cnfa.nstates > 0);
B
Bruce Momjian 已提交
1205
	assert(t->left->flags & SHORTER);
1206 1207

	/* concatenation -- need to split the substring between parts */
1208 1209 1210 1211
	d = getsubdfa(v, t->left);
	NOERR();
	d2 = getsubdfa(v, t->right);
	NOERR();
1212
	MDEBUG(("crev %d\n", t->id));
1213 1214

	/* pick a tentative midpoint */
1215 1216 1217 1218
	mid = shortest(v, d, begin, begin, end, (chr **) NULL, (int *) NULL);
	if (mid == NULL)
		return REG_NOMATCH;
	MDEBUG(("tentative midpoint %ld\n", LOFF(mid)));
1219 1220

	/* iterate until satisfaction or failure */
B
Bruce Momjian 已提交
1221 1222
	for (;;)
	{
1223
		/* try this midpoint on for size */
1224
		if (longest(v, d2, mid, end, (int *) NULL) == end)
B
Bruce Momjian 已提交
1225
		{
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
			er = cdissect(v, t->left, begin, mid);
			if (er == REG_OKAY)
			{
				er = cdissect(v, t->right, mid, end);
				if (er == REG_OKAY)
				{
					/* satisfaction */
					MDEBUG(("successful\n"));
					return REG_OKAY;
				}
			}
			if (er != REG_OKAY && er != REG_NOMATCH)
				return er;
1239 1240 1241
		}

		/* that midpoint didn't work, find a new one */
B
Bruce Momjian 已提交
1242 1243
		if (mid == end)
		{
1244
			/* all possibilities exhausted */
1245
			MDEBUG(("%d no midpoint\n", t->id));
1246 1247
			return REG_NOMATCH;
		}
B
Bruce Momjian 已提交
1248 1249 1250
		mid = shortest(v, d, begin, mid + 1, end, (chr **) NULL, (int *) NULL);
		if (mid == NULL)
		{
1251
			/* failed to find a new one */
1252
			MDEBUG(("%d failed midpoint\n", t->id));
1253 1254
			return REG_NOMATCH;
		}
1255 1256 1257
		MDEBUG(("%d: new midpoint %ld\n", t->id, LOFF(mid)));
		zaptreesubs(v, t->left);
		zaptreesubs(v, t->right);
1258 1259
	}

1260 1261
	/* can't get here */
	return REG_ASSERT;
1262 1263 1264 1265 1266
}

/*
 * cbrdissect - determine backref subexpression matches
 */
B
Bruce Momjian 已提交
1267 1268 1269
static int						/* regexec return code */
cbrdissect(struct vars * v,
		   struct subre * t,
1270 1271
		   chr *begin,			/* beginning of relevant substring */
		   chr *end)			/* end of same */
1272
{
B
Bruce Momjian 已提交
1273
	int			n = t->subno;
1274 1275 1276 1277
	size_t		numreps;
	size_t		tlen;
	size_t		brlen;
	chr		   *brstring;
B
Bruce Momjian 已提交
1278 1279 1280
	chr		   *p;
	int			min = t->min;
	int			max = t->max;
1281 1282 1283 1284

	assert(t != NULL);
	assert(t->op == 'b');
	assert(n >= 0);
B
Bruce Momjian 已提交
1285
	assert((size_t) n < v->nmatch);
1286

1287
	MDEBUG(("cbackref n%d %d{%d-%d}\n", t->id, n, min, max));
1288

1289
	/* get the backreferenced string */
1290 1291
	if (v->pmatch[n].rm_so == -1)
		return REG_NOMATCH;
1292 1293
	brstring = v->start + v->pmatch[n].rm_so;
	brlen = v->pmatch[n].rm_eo - v->pmatch[n].rm_so;
1294

1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
	/* special cases for zero-length strings */
	if (brlen == 0)
	{
		/*
		 * matches only if target is zero length, but any number of
		 * repetitions can be considered to be present
		 */
		if (begin == end && min <= max)
		{
			MDEBUG(("cbackref matched trivially\n"));
			return REG_OKAY;
		}
		return REG_NOMATCH;
	}
	if (begin == end)
B
Bruce Momjian 已提交
1310
	{
1311 1312 1313 1314
		/* matches only if zero repetitions are okay */
		if (min == 0)
		{
			MDEBUG(("cbackref matched trivially\n"));
1315
			return REG_OKAY;
1316
		}
1317 1318 1319
		return REG_NOMATCH;
	}

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
	/*
	 * check target length to see if it could possibly be an allowed number of
	 * repetitions of brstring
	 */
	assert(end > begin);
	tlen = end - begin;
	if (tlen % brlen != 0)
		return REG_NOMATCH;
	numreps = tlen / brlen;
	if (numreps < min || (numreps > max && max != INFINITY))
1330 1331
		return REG_NOMATCH;

1332 1333 1334
	/* okay, compare the actual string contents */
	p = begin;
	while (numreps-- > 0)
B
Bruce Momjian 已提交
1335
	{
1336 1337 1338
		if ((*v->g->compare) (brstring, p, brlen) != 0)
			return REG_NOMATCH;
		p += brlen;
1339 1340
	}

1341 1342
	MDEBUG(("cbackref matched\n"));
	return REG_OKAY;
1343 1344 1345 1346 1347
}

/*
 * caltdissect - determine alternative subexpression matches (w. complications)
 */
B
Bruce Momjian 已提交
1348 1349 1350
static int						/* regexec return code */
caltdissect(struct vars * v,
			struct subre * t,
1351 1352
			chr *begin,			/* beginning of relevant substring */
			chr *end)			/* end of same */
1353 1354
{
	struct dfa *d;
B
Bruce Momjian 已提交
1355 1356
	int			er;

1357 1358 1359
	if (t == NULL)
		return REG_NOMATCH;

1360
	assert(t->op == '|');
1361 1362
	assert(t->left != NULL);

1363 1364
	MDEBUG(("calt n%d\n", t->id));

1365 1366
	d = getsubdfa(v, t->left);
	NOERR();
1367 1368 1369
	if (longest(v, d, begin, end, (int *) NULL) != end)
		return caltdissect(v, t->right, begin, end);
	MDEBUG(("calt matched\n"));
1370 1371 1372 1373 1374 1375 1376 1377

	er = cdissect(v, t->left, begin, end);
	if (er != REG_NOMATCH)
		return er;

	return caltdissect(v, t->right, begin, end);
}

1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
/*
 * citerdissect - iteration subexpression matches (with complications)
 */
static int						/* regexec return code */
citerdissect(struct vars * v,
			 struct subre * t,
			 chr *begin,		/* beginning of relevant substring */
			 chr *end)			/* end of same */
{
	struct dfa *d;
	chr		  **endpts;
	chr		   *limit;
	int			min_matches;
	size_t		max_matches;
	int			nverified;
	int			k;
	int			i;
	int			er;

	assert(t->op == '*');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(begin <= end);

	if (t->left->flags & SHORTER)		/* reverse scan */
		return creviterdissect(v, t, begin, end);

	/*
	 * If zero matches are allowed, and target string is empty, just declare
	 * victory.  OTOH, if target string isn't empty, zero matches can't work
	 * so we pretend the min is 1.
	 */
	min_matches = t->min;
	if (min_matches <= 0)
	{
		if (begin == end)
			return REG_OKAY;
		min_matches = 1;
	}

	/*
	 * We need workspace to track the endpoints of each sub-match.  Normally
	 * we consider only nonzero-length sub-matches, so there can be at most
	 * end-begin of them.  However, if min is larger than that, we will also
	 * consider zero-length sub-matches in order to find enough matches.
	 *
	 * For convenience, endpts[0] contains the "begin" pointer and we store
	 * sub-match endpoints in endpts[1..max_matches].
	 */
	max_matches = end - begin;
	if (max_matches > t->max && t->max != INFINITY)
		max_matches = t->max;
	if (max_matches < min_matches)
		max_matches = min_matches;
	endpts = (chr **) MALLOC((max_matches + 1) * sizeof(chr *));
	if (endpts == NULL)
		return REG_ESPACE;
	endpts[0] = begin;

1436
	d = getsubdfa(v, t->left);
1437 1438 1439 1440 1441
	if (ISERR())
	{
		FREE(endpts);
		return v->err;
	}
1442
	MDEBUG(("citer %d\n", t->id));
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470

	/*
	 * Our strategy is to first find a set of sub-match endpoints that are
	 * valid according to the child node's DFA, and then recursively dissect
	 * each sub-match to confirm validity.  If any validity check fails,
	 * backtrack the last sub-match and try again.  And, when we next try for
	 * a validity check, we need not recheck any successfully verified
	 * sub-matches that we didn't move the endpoints of.  nverified remembers
	 * how many sub-matches are currently known okay.
	 */

	/* initialize to consider first sub-match */
	nverified = 0;
	k = 1;
	limit = end;

	/* iterate until satisfaction or failure */
	while (k > 0)
	{
		/* try to find an endpoint for the k'th sub-match */
		endpts[k] = longest(v, d, endpts[k - 1], limit, (int *) NULL);
		if (endpts[k] == NULL)
		{
			/* no match possible, so see if we can shorten previous one */
			k--;
			goto backtrack;
		}
		MDEBUG(("%d: working endpoint %d: %ld\n",
1471
				t->id, k, LOFF(endpts[k])));
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505

		/* k'th sub-match can no longer be considered verified */
		if (nverified >= k)
			nverified = k - 1;

		if (endpts[k] != end)
		{
			/* haven't reached end yet, try another iteration if allowed */
			if (k >= max_matches)
			{
				/* must try to shorten some previous match */
				k--;
				goto backtrack;
			}

			/* reject zero-length match unless necessary to achieve min */
			if (endpts[k] == endpts[k - 1] &&
				(k >= min_matches || min_matches - k < end - endpts[k]))
				goto backtrack;

			k++;
			limit = end;
			continue;
		}

		/*
		 * We've identified a way to divide the string into k sub-matches
		 * that works so far as the child DFA can tell.  If k is an allowed
		 * number of matches, start the slow part: recurse to verify each
		 * sub-match.  We always have k <= max_matches, needn't check that.
		 */
		if (k < min_matches)
			goto backtrack;

1506
		MDEBUG(("%d: verifying %d..%d\n", t->id, nverified + 1, k));
1507 1508 1509

		for (i = nverified + 1; i <= k; i++)
		{
1510
			zaptreesubs(v, t->left);
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
			er = cdissect(v, t->left, endpts[i - 1], endpts[i]);
			if (er == REG_OKAY)
			{
				nverified = i;
				continue;
			}
			if (er == REG_NOMATCH)
				break;
			/* oops, something failed */
			FREE(endpts);
			return er;
		}

		if (i > k)
		{
			/* satisfaction */
1527
			MDEBUG(("%d successful\n", t->id));
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
			FREE(endpts);
			return REG_OKAY;
		}

		/* match failed to verify, so backtrack */

backtrack:
		/*
		 * Must consider shorter versions of the current sub-match.  However,
		 * we'll only ask for a zero-length match if necessary.
		 */
		while (k > 0)
		{
			chr	   *prev_end = endpts[k - 1];

			if (endpts[k] > prev_end)
			{
				limit = endpts[k] - 1;
				if (limit > prev_end ||
					(k < min_matches && min_matches - k >= end - prev_end))
				{
					/* break out of backtrack loop, continue the outer one */
					break;
				}
			}
			/* can't shorten k'th sub-match any more, consider previous one */
			k--;
		}
	}

	/* all possibilities exhausted */
1559
	MDEBUG(("%d failed\n", t->id));
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
	FREE(endpts);
	return REG_NOMATCH;
}

/*
 * creviterdissect - shortest-first iteration subexpression matches
 */
static int						/* regexec return code */
creviterdissect(struct vars * v,
				struct subre * t,
				chr *begin,		/* beginning of relevant substring */
				chr *end)		/* end of same */
{
	struct dfa *d;
	chr		  **endpts;
	chr		   *limit;
	int			min_matches;
	size_t		max_matches;
	int			nverified;
	int			k;
	int			i;
	int			er;

	assert(t->op == '*');
	assert(t->left != NULL && t->left->cnfa.nstates > 0);
	assert(t->left->flags & SHORTER);
	assert(begin <= end);

	/*
	 * If zero matches are allowed, and target string is empty, just declare
	 * victory.  OTOH, if target string isn't empty, zero matches can't work
	 * so we pretend the min is 1.
	 */
	min_matches = t->min;
	if (min_matches <= 0)
	{
		if (begin == end)
			return REG_OKAY;
		min_matches = 1;
	}

	/*
	 * We need workspace to track the endpoints of each sub-match.  Normally
	 * we consider only nonzero-length sub-matches, so there can be at most
	 * end-begin of them.  However, if min is larger than that, we will also
	 * consider zero-length sub-matches in order to find enough matches.
	 *
	 * For convenience, endpts[0] contains the "begin" pointer and we store
	 * sub-match endpoints in endpts[1..max_matches].
	 */
	max_matches = end - begin;
	if (max_matches > t->max && t->max != INFINITY)
		max_matches = t->max;
	if (max_matches < min_matches)
		max_matches = min_matches;
	endpts = (chr **) MALLOC((max_matches + 1) * sizeof(chr *));
	if (endpts == NULL)
		return REG_ESPACE;
	endpts[0] = begin;

1620
	d = getsubdfa(v, t->left);
1621 1622 1623 1624 1625
	if (ISERR())
	{
		FREE(endpts);
		return v->err;
	}
1626
	MDEBUG(("creviter %d\n", t->id));
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661

	/*
	 * Our strategy is to first find a set of sub-match endpoints that are
	 * valid according to the child node's DFA, and then recursively dissect
	 * each sub-match to confirm validity.  If any validity check fails,
	 * backtrack the last sub-match and try again.  And, when we next try for
	 * a validity check, we need not recheck any successfully verified
	 * sub-matches that we didn't move the endpoints of.  nverified remembers
	 * how many sub-matches are currently known okay.
	 */

	/* initialize to consider first sub-match */
	nverified = 0;
	k = 1;
	limit = begin;

	/* iterate until satisfaction or failure */
	while (k > 0)
	{
		/* disallow zero-length match unless necessary to achieve min */
		if (limit == endpts[k - 1] &&
			limit != end &&
			(k >= min_matches || min_matches - k < end - limit))
			limit++;

		/* try to find an endpoint for the k'th sub-match */
		endpts[k] = shortest(v, d, endpts[k - 1], limit, end,
							 (chr **) NULL, (int *) NULL);
		if (endpts[k] == NULL)
		{
			/* no match possible, so see if we can lengthen previous one */
			k--;
			goto backtrack;
		}
		MDEBUG(("%d: working endpoint %d: %ld\n",
1662
				t->id, k, LOFF(endpts[k])));
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691

		/* k'th sub-match can no longer be considered verified */
		if (nverified >= k)
			nverified = k - 1;

		if (endpts[k] != end)
		{
			/* haven't reached end yet, try another iteration if allowed */
			if (k >= max_matches)
			{
				/* must try to lengthen some previous match */
				k--;
				goto backtrack;
			}

			k++;
			limit = endpts[k - 1];
			continue;
		}

		/*
		 * We've identified a way to divide the string into k sub-matches
		 * that works so far as the child DFA can tell.  If k is an allowed
		 * number of matches, start the slow part: recurse to verify each
		 * sub-match.  We always have k <= max_matches, needn't check that.
		 */
		if (k < min_matches)
			goto backtrack;

1692
		MDEBUG(("%d: verifying %d..%d\n", t->id, nverified + 1, k));
1693 1694 1695

		for (i = nverified + 1; i <= k; i++)
		{
1696
			zaptreesubs(v, t->left);
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
			er = cdissect(v, t->left, endpts[i - 1], endpts[i]);
			if (er == REG_OKAY)
			{
				nverified = i;
				continue;
			}
			if (er == REG_NOMATCH)
				break;
			/* oops, something failed */
			FREE(endpts);
			return er;
		}

		if (i > k)
		{
			/* satisfaction */
1713
			MDEBUG(("%d successful\n", t->id));
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
			FREE(endpts);
			return REG_OKAY;
		}

		/* match failed to verify, so backtrack */

backtrack:
		/*
		 * Must consider longer versions of the current sub-match.
		 */
		while (k > 0)
		{
			if (endpts[k] < end)
			{
				limit = endpts[k] + 1;
				/* break out of backtrack loop, continue the outer one */
				break;
			}
			/* can't lengthen k'th sub-match any more, consider previous one */
			k--;
		}
	}

	/* all possibilities exhausted */
1738
	MDEBUG(("%d failed\n", t->id));
1739 1740 1741 1742
	FREE(endpts);
	return REG_NOMATCH;
}

1743 1744 1745


#include "rege_dfa.c"