exec.go 8.25 KB
Newer Older
1 2 3 4
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

5 6
package regexp

7 8 9 10
import (
	"io"
	"regexp/syntax"
)
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

// A queue is a 'sparse array' holding pending threads of execution.
// See http://research.swtch.com/2008/03/using-uninitialized-memory-for-fun-and.html
type queue struct {
	sparse []uint32
	dense  []entry
}

// A entry is an entry on a queue.
// It holds both the instruction pc and the actual thread.
// Some queue entries are just place holders so that the machine
// knows it has considered that pc.  Such entries have t == nil.
type entry struct {
	pc uint32
	t  *thread
}

// A thread is the state of a single path through the machine:
// an instruction and a corresponding capture array.
// See http://swtch.com/~rsc/regexp/regexp2.html
type thread struct {
	inst *syntax.Inst
	cap  []int
}

// A machine holds all the state during an NFA simulation for p.
type machine struct {
	re       *Regexp      // corresponding Regexp
	p        *syntax.Prog // compiled program
	q0, q1   queue        // two queues for runq, nextq
	pool     []*thread    // pool of available threads
	matched  bool         // whether a match was found
	matchcap []int        // capture information for the match
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

	// cached inputs, to avoid allocation
	inputBytes  inputBytes
	inputString inputString
	inputReader inputReader
}

func (m *machine) newInputBytes(b []byte) input {
	m.inputBytes.str = b
	return &m.inputBytes
}

func (m *machine) newInputString(s string) input {
	m.inputString.str = s
	return &m.inputString
}

func (m *machine) newInputReader(r io.RuneReader) input {
	m.inputReader.r = r
	m.inputReader.atEOT = false
	m.inputReader.pos = 0
	return &m.inputReader
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
}

// progMachine returns a new machine running the prog p.
func progMachine(p *syntax.Prog) *machine {
	m := &machine{p: p}
	n := len(m.p.Inst)
	m.q0 = queue{make([]uint32, n), make([]entry, 0, n)}
	m.q1 = queue{make([]uint32, n), make([]entry, 0, n)}
	ncap := p.NumCap
	if ncap < 2 {
		ncap = 2
	}
	m.matchcap = make([]int, ncap)
	return m
}

82 83 84 85 86 87 88
func (m *machine) init(ncap int) {
	for _, t := range m.pool {
		t.cap = t.cap[:ncap]
	}
	m.matchcap = m.matchcap[:ncap]
}

89 90 91 92 93 94 95 96 97
// alloc allocates a new thread with the given instruction.
// It uses the free pool if possible.
func (m *machine) alloc(i *syntax.Inst) *thread {
	var t *thread
	if n := len(m.pool); n > 0 {
		t = m.pool[n-1]
		m.pool = m.pool[:n-1]
	} else {
		t = new(thread)
98
		t.cap = make([]int, len(m.matchcap), cap(m.matchcap))
99 100 101 102 103 104 105
	}
	t.inst = i
	return t
}

// free returns t to the free pool.
func (m *machine) free(t *thread) {
106 107 108
	m.inputBytes.str = nil
	m.inputString.str = ""
	m.inputReader.r = nil
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	m.pool = append(m.pool, t)
}

// match runs the machine over the input starting at pos.
// It reports whether a match was found.
// If so, m.matchcap holds the submatch information.
func (m *machine) match(i input, pos int) bool {
	startCond := m.re.cond
	if startCond == ^syntax.EmptyOp(0) { // impossible
		return false
	}
	m.matched = false
	for i := range m.matchcap {
		m.matchcap[i] = -1
	}
	runq, nextq := &m.q0, &m.q1
125
	r, r1 := endOfText, endOfText
126
	width, width1 := 0, 0
127 128 129
	r, width = i.step(pos)
	if r != endOfText {
		r1, width1 = i.step(pos + width)
130 131 132
	}
	var flag syntax.EmptyOp
	if pos == 0 {
133
		flag = syntax.EmptyOpContext(-1, r)
134 135
	} else {
		flag = i.context(pos)
136 137 138 139 140 141 142 143 144 145 146
	}
	for {
		if len(runq.dense) == 0 {
			if startCond&syntax.EmptyBeginText != 0 && pos != 0 {
				// Anchored match, past beginning of text.
				break
			}
			if m.matched {
				// Have match; finished exploring alternatives.
				break
			}
147
			if len(m.re.prefix) > 0 && r1 != m.re.prefixRune && i.canCheckPrefix() {
148 149 150 151 152 153
				// Match requires literal prefix; fast search for it.
				advance := i.index(m.re, pos)
				if advance < 0 {
					break
				}
				pos += advance
154 155
				r, width = i.step(pos)
				r1, width1 = i.step(pos + width)
156 157 158 159 160 161
			}
		}
		if !m.matched {
			if len(m.matchcap) > 0 {
				m.matchcap[0] = pos
			}
162
			m.add(runq, uint32(m.p.Start), pos, m.matchcap, flag, nil)
163
		}
164 165
		flag = syntax.EmptyOpContext(r, r1)
		m.step(runq, nextq, pos, pos+width, r, flag)
166 167 168
		if width == 0 {
			break
		}
169 170 171 172 173
		if len(m.matchcap) == 0 && m.matched {
			// Found a match and not paying attention
			// to where it is, so any match will do.
			break
		}
174
		pos += width
175 176 177
		r, width = r1, width1
		if r != endOfText {
			r1, width1 = i.step(pos + width)
178 179 180 181 182 183 184 185 186 187 188
		}
		runq, nextq = nextq, runq
	}
	m.clear(nextq)
	return m.matched
}

// clear frees all threads on the thread queue.
func (m *machine) clear(q *queue) {
	for _, d := range q.dense {
		if d.t != nil {
189 190
			// m.free(d.t)
			m.pool = append(m.pool, d.t)
191 192 193 194 195 196 197 198 199 200
		}
	}
	q.dense = q.dense[:0]
}

// step executes one step of the machine, running each of the threads
// on runq and appending new threads to nextq.
// The step processes the rune c (which may be endOfText),
// which starts at position pos and ends at nextPos.
// nextCond gives the setting for the empty-width flags after c.
201
func (m *machine) step(runq, nextq *queue, pos, nextPos int, c rune, nextCond syntax.EmptyOp) {
202
	longest := m.re.longest
203 204 205 206 207 208
	for j := 0; j < len(runq.dense); j++ {
		d := &runq.dense[j]
		t := d.t
		if t == nil {
			continue
		}
209 210 211 212 213
		if longest && m.matched && len(t.cap) > 0 && m.matchcap[0] < t.cap[0] {
			// m.free(t)
			m.pool = append(m.pool, t)
			continue
		}
214
		i := t.inst
215
		add := false
216 217 218 219 220
		switch i.Op {
		default:
			panic("bad inst")

		case syntax.InstMatch:
221
			if len(t.cap) > 0 && (!longest || !m.matched || m.matchcap[1] < pos) {
222 223 224
				t.cap[1] = pos
				copy(m.matchcap, t.cap)
			}
225 226 227 228 229 230 231
			if !longest {
				// First-match mode: cut off all lower-priority threads.
				for _, d := range runq.dense[j+1:] {
					if d.t != nil {
						// m.free(d.t)
						m.pool = append(m.pool, d.t)
					}
232
				}
233
				runq.dense = runq.dense[:0]
234
			}
235
			m.matched = true
236 237

		case syntax.InstRune:
238 239 240 241 242 243 244 245 246 247 248 249 250 251
			add = i.MatchRune(c)
		case syntax.InstRune1:
			add = c == i.Rune[0]
		case syntax.InstRuneAny:
			add = true
		case syntax.InstRuneAnyNotNL:
			add = c != '\n'
		}
		if add {
			t = m.add(nextq, i.Out, nextPos, t.cap, nextCond, t)
		}
		if t != nil {
			// m.free(t)
			m.pool = append(m.pool, t)
252 253 254 255 256 257 258 259 260
		}
	}
	runq.dense = runq.dense[:0]
}

// add adds an entry to q for pc, unless the q already has such an entry.
// It also recursively adds an entry for all instructions reachable from pc by following
// empty-width conditions satisfied by cond.  pos gives the current position
// in the input.
261
func (m *machine) add(q *queue, pc uint32, pos int, cap []int, cond syntax.EmptyOp, t *thread) *thread {
262
	if pc == 0 {
263
		return t
264 265
	}
	if j := q.sparse[pc]; j < uint32(len(q.dense)) && q.dense[j].pc == pc {
266
		return t
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	}

	j := len(q.dense)
	q.dense = q.dense[:j+1]
	d := &q.dense[j]
	d.t = nil
	d.pc = pc
	q.sparse[pc] = uint32(j)

	i := &m.p.Inst[pc]
	switch i.Op {
	default:
		panic("unhandled")
	case syntax.InstFail:
		// nothing
	case syntax.InstAlt, syntax.InstAltMatch:
283 284
		t = m.add(q, i.Out, pos, cap, cond, t)
		t = m.add(q, i.Arg, pos, cap, cond, t)
285 286
	case syntax.InstEmptyWidth:
		if syntax.EmptyOp(i.Arg)&^cond == 0 {
287
			t = m.add(q, i.Out, pos, cap, cond, t)
288 289
		}
	case syntax.InstNop:
290
		t = m.add(q, i.Out, pos, cap, cond, t)
291 292 293 294
	case syntax.InstCapture:
		if int(i.Arg) < len(cap) {
			opos := cap[i.Arg]
			cap[i.Arg] = pos
295
			m.add(q, i.Out, pos, cap, cond, nil)
296 297
			cap[i.Arg] = opos
		} else {
298
			t = m.add(q, i.Out, pos, cap, cond, t)
299
		}
300 301 302 303 304 305 306
	case syntax.InstMatch, syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
		if t == nil {
			t = m.alloc(i)
		} else {
			t.inst = i
		}
		if len(cap) > 0 && &t.cap[0] != &cap[0] {
307 308 309
			copy(t.cap, cap)
		}
		d.t = t
310
		t = nil
311
	}
312
	return t
313 314 315 316 317 318 319 320 321
}

// empty is a non-nil 0-element slice,
// so doExecute can avoid an allocation
// when 0 captures are requested from a successful match.
var empty = make([]int, 0)

// doExecute finds the leftmost match in the input and returns
// the position of its subexpressions.
322
func (re *Regexp) doExecute(r io.RuneReader, b []byte, s string, pos int, ncap int) []int {
323
	m := re.get()
324 325 326 327 328 329 330 331
	var i input
	if r != nil {
		i = m.newInputReader(r)
	} else if b != nil {
		i = m.newInputBytes(b)
	} else {
		i = m.newInputString(s)
	}
332
	m.init(ncap)
333 334 335 336 337 338 339 340 341 342 343 344 345
	if !m.match(i, pos) {
		re.put(m)
		return nil
	}
	if ncap == 0 {
		re.put(m)
		return empty // empty but not nil
	}
	cap := make([]int, ncap)
	copy(cap, m.matchcap)
	re.put(m)
	return cap
}