Debian Codegraph @

src/pattern.go

raw
1 package fzf
2
3 import (
4 "fmt"
5 "regexp"
6 "strings"
7
8 "github.com/junegunn/fzf/src/algo"
9 "github.com/junegunn/fzf/src/util"
10 )
11
12 // fuzzy
13 // 'exact
14 // ^prefix-exact
15 // suffix-exact$
16 // !inverse-exact
17 // !'inverse-fuzzy
18 // !^inverse-prefix-exact
19 // !inverse-suffix-exact$
20
21 type termType int
22
23 const (
24 termFuzzy termType = iota
25 termExact
26 termExactBoundary
27 termPrefix
28 termSuffix
29 termEqual
30 )
31
32 type term struct {
33 typ termType
34 inv bool
35 text []rune
36 caseSensitive bool
37 normalize bool
38 }
39
40 // String returns the string representation of a term.
41 func (t term) String() string {
42 return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)
43 }
44
45 type termSet []term
46
47 // Pattern represents search pattern
48 type Pattern struct {
49 fuzzy bool
50 fuzzyAlgo algo.Algo
51 extended bool
52 caseSensitive bool
53 normalize bool
54 forward bool
55 withPos bool
56 text []rune
57 termSets []termSet
58 sortable bool
59 cacheable bool
60 cacheKey string
61 delimiter Delimiter
62 nth []Range
63 revision revision
64 procFun [6]algo.Algo
65 cache *ChunkCache
66 denylist map[int32]struct{}
67 startIndex int32
68 directAlgo algo.Algo
69 directTerm *term
70 }
71
72 var _splitRegex *regexp.Regexp
73
74 func init() {
75 _splitRegex = regexp.MustCompile(" +")
76 }
77
78 // BuildPattern builds Pattern object from the given arguments
79 func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,
80 withPos bool, cacheable bool, nth []Range, delimiter Delimiter, revision revision, runes []rune, denylist map[int32]struct{}, startIndex int32) *Pattern {
81
82 var asString string
83 if extended {
84 asString = strings.TrimLeft(string(runes), " ")
85 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {
86 asString = asString[:len(asString)-1]
87 }
88 } else {
89 asString = string(runes)
90 }
91
92 // We can uniquely identify the pattern for a given string since
93 // search mode and caseMode do not change while the program is running
94 cached, found := patternCache[asString]
95 if found {
96 return cached
97 }
98
99 caseSensitive := true
100 sortable := true
101 termSets := []termSet{}
102
103 if extended {
104 termSets = parseTerms(fuzzy, caseMode, normalize, asString)
105 // We should not sort the result if there are only inverse search terms
106 sortable = false
107 Loop:
108 for _, termSet := range termSets {
109 for idx, term := range termSet {
110 if !term.inv {
111 sortable = true
112 }
113 // If the query contains inverse search terms or OR operators,
114 // we cannot cache the search scope
115 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {
116 cacheable = false
117 if sortable {
118 // Can't break until we see at least one non-inverse term
119 break Loop
120 }
121 }
122 }
123 }
124 } else {
125 lowerString := strings.ToLower(asString)
126 normalize = normalize &&
127 lowerString == string(algo.NormalizeRunes([]rune(lowerString)))
128 caseSensitive = caseMode == CaseRespect ||
129 caseMode == CaseSmart && lowerString != asString
130 if !caseSensitive {
131 asString = lowerString
132 }
133 }
134
135 ptr := &Pattern{
136 fuzzy: fuzzy,
137 fuzzyAlgo: fuzzyAlgo,
138 extended: extended,
139 caseSensitive: caseSensitive,
140 normalize: normalize,
141 forward: forward,
142 withPos: withPos,
143 text: []rune(asString),
144 termSets: termSets,
145 sortable: sortable,
146 cacheable: cacheable,
147 nth: nth,
148 revision: revision,
149 delimiter: delimiter,
150 cache: cache,
151 denylist: denylist,
152 startIndex: startIndex,
153 }
154
155 ptr.cacheKey = ptr.buildCacheKey()
156 ptr.directAlgo, ptr.directTerm = ptr.buildDirectAlgo(fuzzyAlgo)
157 ptr.procFun[termFuzzy] = fuzzyAlgo
158 ptr.procFun[termEqual] = algo.EqualMatch
159 ptr.procFun[termExact] = algo.ExactMatchNaive
160 ptr.procFun[termExactBoundary] = algo.ExactMatchBoundary
161 ptr.procFun[termPrefix] = algo.PrefixMatch
162 ptr.procFun[termSuffix] = algo.SuffixMatch
163
164 patternCache[asString] = ptr
165 return ptr
166 }
167
168 func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {
169 str = strings.ReplaceAll(str, "\\ ", "\t")
170 tokens := _splitRegex.Split(str, -1)
171 sets := []termSet{}
172 set := termSet{}
173 switchSet := false
174 afterBar := false
175 for _, token := range tokens {
176 typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")
177 lowerText := strings.ToLower(text)
178 caseSensitive := caseMode == CaseRespect ||
179 caseMode == CaseSmart && text != lowerText
180 normalizeTerm := normalize &&
181 lowerText == string(algo.NormalizeRunes([]rune(lowerText)))
182 if !caseSensitive {
183 text = lowerText
184 }
185 if !fuzzy {
186 typ = termExact
187 }
188
189 if len(set) > 0 && !afterBar && text == "|" {
190 switchSet = false
191 afterBar = true
192 continue
193 }
194 afterBar = false
195
196 if strings.HasPrefix(text, "!") {
197 inv = true
198 typ = termExact
199 text = text[1:]
200 }
201
202 if text != "$" && strings.HasSuffix(text, "$") {
203 typ = termSuffix
204 text = text[:len(text)-1]
205 }
206
207 if len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {
208 typ = termExactBoundary
209 text = text[1 : len(text)-1]
210 } else if strings.HasPrefix(text, "'") {
211 // Flip exactness
212 if fuzzy && !inv {
213 typ = termExact
214 } else {
215 typ = termFuzzy
216 }
217 text = text[1:]
218 } else if strings.HasPrefix(text, "^") {
219 if typ == termSuffix {
220 typ = termEqual
221 } else {
222 typ = termPrefix
223 }
224 text = text[1:]
225 }
226
227 if len(text) > 0 {
228 if switchSet {
229 sets = append(sets, set)
230 set = termSet{}
231 }
232 textRunes := []rune(text)
233 if normalizeTerm {
234 textRunes = algo.NormalizeRunes(textRunes)
235 }
236 set = append(set, term{
237 typ: typ,
238 inv: inv,
239 text: textRunes,
240 caseSensitive: caseSensitive,
241 normalize: normalizeTerm})
242 switchSet = true
243 }
244 }
245 if len(set) > 0 {
246 sets = append(sets, set)
247 }
248 return sets
249 }
250
251 // IsEmpty returns true if the pattern is effectively empty
252 func (p *Pattern) IsEmpty() bool {
253 if len(p.denylist) > 0 {
254 return false
255 }
256 if !p.extended {
257 return len(p.text) == 0
258 }
259 return len(p.termSets) == 0
260 }
261
262 // AsString returns the search query in string type
263 func (p *Pattern) AsString() string {
264 return string(p.text)
265 }
266
267 func (p *Pattern) buildCacheKey() string {
268 if !p.extended {
269 return p.AsString()
270 }
271 cacheableTerms := []string{}
272 for _, termSet := range p.termSets {
273 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {
274 cacheableTerms = append(cacheableTerms, string(termSet[0].text))
275 }
276 }
277 return strings.Join(cacheableTerms, "\t")
278 }
279
280 // buildDirectAlgo returns the algo function and term for the direct fast path
281 // in matchChunk. Returns (nil, nil) if the pattern is not suitable.
282 // Requirements: extended mode, single term set with single non-inverse fuzzy term, no nth.
283 func (p *Pattern) buildDirectAlgo(fuzzyAlgo algo.Algo) (algo.Algo, *term) {
284 if !p.extended || len(p.nth) > 0 {
285 return nil, nil
286 }
287 if len(p.termSets) == 1 && len(p.termSets[0]) == 1 {
288 t := &p.termSets[0][0]
289 if !t.inv && t.typ == termFuzzy {
290 return fuzzyAlgo, t
291 }
292 }
293 return nil, nil
294 }
295
296 // CacheKey is used to build string to be used as the key of result cache
297 func (p *Pattern) CacheKey() string {
298 return p.cacheKey
299 }
300
301 // Match returns the list of matches Items in the given Chunk
302 func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {
303 cacheKey := p.CacheKey()
304
305 // Bitmap cache: exact match or prefix/suffix
306 var cachedBitmap *ChunkBitmap
307 if p.cacheable {
308 cachedBitmap = p.cache.Lookup(chunk, cacheKey)
309 }
310 if cachedBitmap == nil {
311 cachedBitmap = p.cache.Search(chunk, cacheKey)
312 }
313
314 matches, bitmap := p.matchChunk(chunk, cachedBitmap, slab)
315
316 if p.cacheable {
317 p.cache.Add(chunk, cacheKey, bitmap, len(matches))
318 }
319 return matches
320 }
321
322 func (p *Pattern) matchChunk(chunk *Chunk, cachedBitmap *ChunkBitmap, slab *util.Slab) ([]Result, ChunkBitmap) {
323 matches := []Result{}
324 var bitmap ChunkBitmap
325
326 // Skip header items in chunks that contain them
327 startIdx := 0
328 if p.startIndex > 0 && chunk.count > 0 && chunk.items[0].Index() < p.startIndex {
329 startIdx = int(p.startIndex - chunk.items[0].Index())
330 if startIdx >= chunk.count {
331 return matches, bitmap
332 }
333 }
334
335 hasCachedBitmap := cachedBitmap != nil
336
337 // Fast path: single fuzzy term, no nth, no denylist.
338 // Calls the algo function directly, bypassing MatchItem/extendedMatch/iter
339 // and avoiding per-match []Offset heap allocation.
340 if p.directAlgo != nil && len(p.denylist) == 0 {
341 t := p.directTerm
342 for idx := startIdx; idx < chunk.count; idx++ {
343 if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {
344 continue
345 }
346 res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,
347 &chunk.items[idx].text, t.text, p.withPos, slab)
348 if res.Start >= 0 {
349 bitmap[idx/64] |= uint64(1) << (idx % 64)
350 matches = append(matches, buildResultFromBounds(
351 &chunk.items[idx], res.Score,
352 int(res.Start), int(res.End), int(res.End), true))
353 }
354 }
355 return matches, bitmap
356 }
357
358 if len(p.denylist) == 0 {
359 for idx := startIdx; idx < chunk.count; idx++ {
360 if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {
361 continue
362 }
363 if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {
364 bitmap[idx/64] |= uint64(1) << (idx % 64)
365 matches = append(matches, match)
366 }
367 }
368 return matches, bitmap
369 }
370
371 for idx := startIdx; idx < chunk.count; idx++ {
372 if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {
373 continue
374 }
375 if _, prs := p.denylist[chunk.items[idx].Index()]; prs {
376 continue
377 }
378 if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {
379 bitmap[idx/64] |= uint64(1) << (idx % 64)
380 matches = append(matches, match)
381 }
382 }
383 return matches, bitmap
384 }
385
386 // MatchItem returns the match result if the Item is a match.
387 // A zero-value Result (with item == nil) indicates no match.
388 func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (Result, []Offset, *[]int) {
389 if p.extended {
390 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {
391 return buildResult(item, offsets, bonus), offsets, pos
392 }
393 return Result{}, nil, nil
394 }
395 offset, bonus, pos := p.basicMatch(item, withPos, slab)
396 if sidx := offset[0]; sidx >= 0 {
397 offsets := []Offset{offset}
398 return buildResult(item, offsets, bonus), offsets, pos
399 }
400 return Result{}, nil, nil
401 }
402
403 func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {
404 var input []Token
405 if len(p.nth) == 0 {
406 input = []Token{{text: &item.text, prefixLength: 0}}
407 } else {
408 input = p.transformInput(item)
409 }
410 if p.fuzzy {
411 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
412 }
413 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)
414 }
415
416 func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {
417 var input []Token
418 if len(p.nth) == 0 {
419 input = []Token{{text: &item.text, prefixLength: 0}}
420 } else {
421 input = p.transformInput(item)
422 }
423 offsets := []Offset{}
424 var totalScore int
425 var allPos *[]int
426 if withPos {
427 allPos = &[]int{}
428 }
429 for _, termSet := range p.termSets {
430 var offset Offset
431 var currentScore int
432 matched := false
433 for _, term := range termSet {
434 pfun := p.procFun[term.typ]
435 off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)
436 if sidx := off[0]; sidx >= 0 {
437 if term.inv {
438 continue
439 }
440 offset, currentScore = off, score
441 matched = true
442 if withPos {
443 if pos != nil {
444 *allPos = append(*allPos, *pos...)
445 } else {
446 for idx := off[0]; idx < off[1]; idx++ {
447 *allPos = append(*allPos, int(idx))
448 }
449 }
450 }
451 break
452 } else if term.inv {
453 offset, currentScore = Offset{0, 0}, 0
454 matched = true
455 continue
456 }
457 }
458 if matched {
459 offsets = append(offsets, offset)
460 totalScore += currentScore
461 }
462 }
463 return offsets, totalScore, allPos
464 }
465
466 func (p *Pattern) transformInput(item *Item) []Token {
467 if item.transformed != nil {
468 transformed := *item.transformed
469 if transformed.revision == p.revision {
470 return transformed.tokens
471 }
472 }
473
474 tokens := Tokenize(item.text.ToString(), p.delimiter)
475 ret := Transform(tokens, p.nth)
476 // Strip the last delimiter to allow suffix match
477 if len(ret) > 0 && !p.delimiter.IsAwk() {
478 chars := ret[len(ret)-1].text
479 stripped := StripLastDelimiter(chars.ToString(), p.delimiter)
480 newChars := util.ToChars(stringBytes(stripped))
481 ret[len(ret)-1].text = &newChars
482 }
483 item.transformed = &transformed{p.revision, ret}
484 return ret
485 }
486
487 func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {
488 for _, part := range tokens {
489 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {
490 sidx := int32(res.Start) + part.prefixLength
491 eidx := int32(res.End) + part.prefixLength
492 if pos != nil {
493 for idx := range *pos {
494 (*pos)[idx] += int(part.prefixLength)
495 }
496 }
497 return Offset{sidx, eidx}, res.Score, pos
498 }
499 }
500 return Offset{-1, -1}, 0, nil
501 }