backtrack.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // backtrack is a regular expression search with submatch
  5. // tracking for small regular expressions and texts. It allocates
  6. // a bit vector with (length of input) * (length of prog) bits,
  7. // to make sure it never explores the same (character position, instruction)
  8. // state multiple times. This limits the search to run in time linear in
  9. // the length of the test.
  10. //
  11. // backtrack is a fast replacement for the NFA code on small
  12. // regexps when onepass cannot be used.
  13. package regexp
  14. import (
  15. "regexp/syntax"
  16. "sync"
  17. )
  18. // A job is an entry on the backtracker's job stack. It holds
  19. // the instruction pc and the position in the input.
  20. type job struct {
  21. pc uint32
  22. arg bool
  23. pos int
  24. }
  25. const (
  26. visitedBits = 32
  27. maxBacktrackProg = 500 // len(prog.Inst) <= max
  28. maxBacktrackVector = 256 * 1024 // bit vector size <= max (bits)
  29. )
  30. // bitState holds state for the backtracker.
  31. type bitState struct {
  32. end int
  33. cap []int
  34. matchcap []int
  35. jobs []job
  36. visited []uint32
  37. inputs inputs
  38. }
  39. var bitStatePool sync.Pool
  40. func newBitState() *bitState {
  41. b, ok := bitStatePool.Get().(*bitState)
  42. if !ok {
  43. b = new(bitState)
  44. }
  45. return b
  46. }
  47. func freeBitState(b *bitState) {
  48. b.inputs.clear()
  49. bitStatePool.Put(b)
  50. }
  51. // maxBitStateLen returns the maximum length of a string to search with
  52. // the backtracker using prog.
  53. func maxBitStateLen(prog *syntax.Prog) int {
  54. if !shouldBacktrack(prog) {
  55. return 0
  56. }
  57. return maxBacktrackVector / len(prog.Inst)
  58. }
  59. // shouldBacktrack reports whether the program is too
  60. // long for the backtracker to run.
  61. func shouldBacktrack(prog *syntax.Prog) bool {
  62. return len(prog.Inst) <= maxBacktrackProg
  63. }
  64. // reset resets the state of the backtracker.
  65. // end is the end position in the input.
  66. // ncap is the number of captures.
  67. func (b *bitState) reset(prog *syntax.Prog, end int, ncap int) {
  68. b.end = end
  69. if cap(b.jobs) == 0 {
  70. b.jobs = make([]job, 0, 256)
  71. } else {
  72. b.jobs = b.jobs[:0]
  73. }
  74. visitedSize := (len(prog.Inst)*(end+1) + visitedBits - 1) / visitedBits
  75. if cap(b.visited) < visitedSize {
  76. b.visited = make([]uint32, visitedSize, maxBacktrackVector/visitedBits)
  77. } else {
  78. b.visited = b.visited[:visitedSize]
  79. for i := range b.visited {
  80. b.visited[i] = 0
  81. }
  82. }
  83. if cap(b.cap) < ncap {
  84. b.cap = make([]int, ncap)
  85. } else {
  86. b.cap = b.cap[:ncap]
  87. }
  88. for i := range b.cap {
  89. b.cap[i] = -1
  90. }
  91. if cap(b.matchcap) < ncap {
  92. b.matchcap = make([]int, ncap)
  93. } else {
  94. b.matchcap = b.matchcap[:ncap]
  95. }
  96. for i := range b.matchcap {
  97. b.matchcap[i] = -1
  98. }
  99. }
  100. // shouldVisit reports whether the combination of (pc, pos) has not
  101. // been visited yet.
  102. func (b *bitState) shouldVisit(pc uint32, pos int) bool {
  103. n := uint(int(pc)*(b.end+1) + pos)
  104. if b.visited[n/visitedBits]&(1<<(n&(visitedBits-1))) != 0 {
  105. return false
  106. }
  107. b.visited[n/visitedBits] |= 1 << (n & (visitedBits - 1))
  108. return true
  109. }
  110. // push pushes (pc, pos, arg) onto the job stack if it should be
  111. // visited.
  112. func (b *bitState) push(re *Regexp, pc uint32, pos int, arg bool) {
  113. // Only check shouldVisit when arg is false.
  114. // When arg is true, we are continuing a previous visit.
  115. if re.prog.Inst[pc].Op != syntax.InstFail && (arg || b.shouldVisit(pc, pos)) {
  116. b.jobs = append(b.jobs, job{pc: pc, arg: arg, pos: pos})
  117. }
  118. }
  119. // tryBacktrack runs a backtracking search starting at pos.
  120. func (re *Regexp) tryBacktrack(b *bitState, i input, pc uint32, pos int) bool {
  121. longest := re.longest
  122. b.push(re, pc, pos, false)
  123. for len(b.jobs) > 0 {
  124. l := len(b.jobs) - 1
  125. // Pop job off the stack.
  126. pc := b.jobs[l].pc
  127. pos := b.jobs[l].pos
  128. arg := b.jobs[l].arg
  129. b.jobs = b.jobs[:l]
  130. // Optimization: rather than push and pop,
  131. // code that is going to Push and continue
  132. // the loop simply updates ip, p, and arg
  133. // and jumps to CheckAndLoop. We have to
  134. // do the ShouldVisit check that Push
  135. // would have, but we avoid the stack
  136. // manipulation.
  137. goto Skip
  138. CheckAndLoop:
  139. if !b.shouldVisit(pc, pos) {
  140. continue
  141. }
  142. Skip:
  143. inst := re.prog.Inst[pc]
  144. switch inst.Op {
  145. default:
  146. panic("bad inst")
  147. case syntax.InstFail:
  148. panic("unexpected InstFail")
  149. case syntax.InstAlt:
  150. // Cannot just
  151. // b.push(inst.Out, pos, false)
  152. // b.push(inst.Arg, pos, false)
  153. // If during the processing of inst.Out, we encounter
  154. // inst.Arg via another path, we want to process it then.
  155. // Pushing it here will inhibit that. Instead, re-push
  156. // inst with arg==true as a reminder to push inst.Arg out
  157. // later.
  158. if arg {
  159. // Finished inst.Out; try inst.Arg.
  160. arg = false
  161. pc = inst.Arg
  162. goto CheckAndLoop
  163. } else {
  164. b.push(re, pc, pos, true)
  165. pc = inst.Out
  166. goto CheckAndLoop
  167. }
  168. case syntax.InstAltMatch:
  169. // One opcode consumes runes; the other leads to match.
  170. switch re.prog.Inst[inst.Out].Op {
  171. case syntax.InstRune, syntax.InstRune1, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
  172. // inst.Arg is the match.
  173. b.push(re, inst.Arg, pos, false)
  174. pc = inst.Arg
  175. pos = b.end
  176. goto CheckAndLoop
  177. }
  178. // inst.Out is the match - non-greedy
  179. b.push(re, inst.Out, b.end, false)
  180. pc = inst.Out
  181. goto CheckAndLoop
  182. case syntax.InstRune:
  183. r, width := i.step(pos)
  184. if !inst.MatchRune(r) {
  185. continue
  186. }
  187. pos += width
  188. pc = inst.Out
  189. goto CheckAndLoop
  190. case syntax.InstRune1:
  191. r, width := i.step(pos)
  192. if r != inst.Rune[0] {
  193. continue
  194. }
  195. pos += width
  196. pc = inst.Out
  197. goto CheckAndLoop
  198. case syntax.InstRuneAnyNotNL:
  199. r, width := i.step(pos)
  200. if r == '\n' || r == endOfText {
  201. continue
  202. }
  203. pos += width
  204. pc = inst.Out
  205. goto CheckAndLoop
  206. case syntax.InstRuneAny:
  207. r, width := i.step(pos)
  208. if r == endOfText {
  209. continue
  210. }
  211. pos += width
  212. pc = inst.Out
  213. goto CheckAndLoop
  214. case syntax.InstCapture:
  215. if arg {
  216. // Finished inst.Out; restore the old value.
  217. b.cap[inst.Arg] = pos
  218. continue
  219. } else {
  220. if inst.Arg < uint32(len(b.cap)) {
  221. // Capture pos to register, but save old value.
  222. b.push(re, pc, b.cap[inst.Arg], true) // come back when we're done.
  223. b.cap[inst.Arg] = pos
  224. }
  225. pc = inst.Out
  226. goto CheckAndLoop
  227. }
  228. case syntax.InstEmptyWidth:
  229. flag := i.context(pos)
  230. if !flag.match(syntax.EmptyOp(inst.Arg)) {
  231. continue
  232. }
  233. pc = inst.Out
  234. goto CheckAndLoop
  235. case syntax.InstNop:
  236. pc = inst.Out
  237. goto CheckAndLoop
  238. case syntax.InstMatch:
  239. // We found a match. If the caller doesn't care
  240. // where the match is, no point going further.
  241. if len(b.cap) == 0 {
  242. return true
  243. }
  244. // Record best match so far.
  245. // Only need to check end point, because this entire
  246. // call is only considering one start position.
  247. if len(b.cap) > 1 {
  248. b.cap[1] = pos
  249. }
  250. if old := b.matchcap[1]; old == -1 || (longest && pos > 0 && pos > old) {
  251. copy(b.matchcap, b.cap)
  252. }
  253. // If going for first match, we're done.
  254. if !longest {
  255. return true
  256. }
  257. // If we used the entire text, no longer match is possible.
  258. if pos == b.end {
  259. return true
  260. }
  261. // Otherwise, continue on in hope of a longer match.
  262. continue
  263. }
  264. }
  265. return longest && len(b.matchcap) > 1 && b.matchcap[1] >= 0
  266. }
  267. // backtrack runs a backtracking search of prog on the input starting at pos.
  268. func (re *Regexp) backtrack(ib []byte, is string, pos int, ncap int, dstCap []int) []int {
  269. startCond := re.cond
  270. if startCond == ^syntax.EmptyOp(0) { // impossible
  271. return nil
  272. }
  273. if startCond&syntax.EmptyBeginText != 0 && pos != 0 {
  274. // Anchored match, past beginning of text.
  275. return nil
  276. }
  277. b := newBitState()
  278. i, end := b.inputs.init(nil, ib, is)
  279. b.reset(re.prog, end, ncap)
  280. // Anchored search must start at the beginning of the input
  281. if startCond&syntax.EmptyBeginText != 0 {
  282. if len(b.cap) > 0 {
  283. b.cap[0] = pos
  284. }
  285. if !re.tryBacktrack(b, i, uint32(re.prog.Start), pos) {
  286. freeBitState(b)
  287. return nil
  288. }
  289. } else {
  290. // Unanchored search, starting from each possible text position.
  291. // Notice that we have to try the empty string at the end of
  292. // the text, so the loop condition is pos <= end, not pos < end.
  293. // This looks like it's quadratic in the size of the text,
  294. // but we are not clearing visited between calls to TrySearch,
  295. // so no work is duplicated and it ends up still being linear.
  296. width := -1
  297. for ; pos <= end && width != 0; pos += width {
  298. if len(re.prefix) > 0 {
  299. // Match requires literal prefix; fast search for it.
  300. advance := i.index(re, pos)
  301. if advance < 0 {
  302. freeBitState(b)
  303. return nil
  304. }
  305. pos += advance
  306. }
  307. if len(b.cap) > 0 {
  308. b.cap[0] = pos
  309. }
  310. if re.tryBacktrack(b, i, uint32(re.prog.Start), pos) {
  311. // Match must be leftmost; done.
  312. goto Match
  313. }
  314. _, width = i.step(pos)
  315. }
  316. freeBitState(b)
  317. return nil
  318. }
  319. Match:
  320. dstCap = append(dstCap, b.matchcap...)
  321. freeBitState(b)
  322. return dstCap
  323. }