backtrack.go 9.0 KB

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