Skip to content
Myr

pattern.go

This file

Path

src/pattern.go

408 lines · 9.7 KiB · Go

Last changed by

Make fzf pass go vetRyan Boehningbefore adoption21b94d2

History of this file

Take it

The walk stopped after 200 commits: lines older than bbe10f4 point at it.

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 1–3why, one step back
1package fzf
23import (

Make fzf pass go vetRyan Boehningbefore adoption21b94d2

line 4why, one step back
4 "fmt"

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 5–13why, one step back
5 "regexp"
6 "strings"78 "github.com/junegunn/fzf/src/algo"9 "github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

lines 14–19why, one step back
14// ^prefix-exact
15// suffix-exact$16// !inverse-exact17// !'inverse-fuzzy18// !^inverse-prefix-exact19// !inverse-suffix-exact$

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 20–35why, one step back
20
21type termType int2223const (24 termFuzzy termType = iota25 termExact26 termPrefix27 termSuffix28 termEqual29)3031type term struct {32 typ termType33 inv bool34 text []rune35 caseSensitive bool

Make fzf pass go vetRyan Boehningbefore adoption21b94d2

lines 36–40why, one step back
36}
3738// String returns the string representation of a term.39func (t term) String() string {40 return fmt.Sprintf("term{typ: %d, inv: %v, text: []rune(%q), caseSensitive: %v}", t.typ, t.inv, string(t.text), t.caseSensitive)

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 41–55why, one step back
41}
4243type termSet []term4445// Pattern represents search pattern46type Pattern struct {47 fuzzy bool48 fuzzyAlgo algo.Algo49 extended bool50 caseSensitive bool51 normalize bool52 forward bool53 text []rune54 termSets []termSet55 cacheable bool

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 56why, one step back
56 cacheKey string

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 57–62why, one step back
57 delimiter Delimiter
58 nth []Range59 procFun map[termType]algo.Algo60}6162var (

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

lines 63–65why, one step back
63 _patternCache map[string]*Pattern
64 _splitRegex *regexp.Regexp65 _cache ChunkCache

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 66–68why, one step back
66)
6768func init() {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 69why, one step back
69 _splitRegex = regexp.MustCompile(" +")

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 70–89why, one step back
70 clearPatternCache()
71 clearChunkCache()72}7374func clearPatternCache() {75 // We can uniquely identify the pattern for a given string since76 // search mode and caseMode do not change while the program is running77 _patternCache = make(map[string]*Pattern)78}7980func clearChunkCache() {81 _cache = NewChunkCache()82}8384// BuildPattern builds Pattern object from the given arguments85func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,86 cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8788 var asString string89 if extended {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

lines 90–93why, one step back
90 asString = strings.TrimLeft(string(runes), " ")
91 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {92 asString = asString[:len(asString)-1]93 }

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 94–112why, one step back
94 } else {
95 asString = string(runes)96 }9798 cached, found := _patternCache[asString]99 if found {100 return cached101 }102103 caseSensitive := true104 termSets := []termSet{}105106 if extended {107 termSets = parseTerms(fuzzy, caseMode, normalize, asString)108 Loop:109 for _, termSet := range termSets {110 for idx, term := range termSet {111 // If the query contains inverse search terms or OR operators,112 // we cannot cache the search scope

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 113why, one step back
113 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 114–141why, one step back
114 cacheable = false
115 break Loop116 }117 }118 }119 } else {120 lowerString := strings.ToLower(asString)121 caseSensitive = caseMode == CaseRespect ||122 caseMode == CaseSmart && lowerString != asString123 if !caseSensitive {124 asString = lowerString125 }126 }127128 ptr := &Pattern{129 fuzzy: fuzzy,130 fuzzyAlgo: fuzzyAlgo,131 extended: extended,132 caseSensitive: caseSensitive,133 normalize: normalize,134 forward: forward,135 text: []rune(asString),136 termSets: termSets,137 cacheable: cacheable,138 nth: nth,139 delimiter: delimiter,140 procFun: make(map[termType]algo.Algo)}141

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 142why, one step back
142 ptr.cacheKey = ptr.buildCacheKey()

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 143–153why, one step back
143 ptr.procFun[termFuzzy] = fuzzyAlgo
144 ptr.procFun[termEqual] = algo.EqualMatch145 ptr.procFun[termExact] = algo.ExactMatchNaive146 ptr.procFun[termPrefix] = algo.PrefixMatch147 ptr.procFun[termSuffix] = algo.SuffixMatch148149 _patternCache[asString] = ptr150 return ptr151}152153func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 154why, one step back
154 str = strings.Replace(str, "\\ ", "\t", -1)

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 155–158why, one step back
155 tokens := _splitRegex.Split(str, -1)
156 sets := []termSet{}157 set := termSet{}158 switchSet := false

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 159why, one step back
159 afterBar := false

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

line 160why, one step back
160 for _, token := range tokens {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 161why, one step back
161 typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 162–171why, one step back
162 lowerText := strings.ToLower(text)
163 caseSensitive := caseMode == CaseRespect ||164 caseMode == CaseSmart && text != lowerText165 if !caseSensitive {166 text = lowerText167 }168 if !fuzzy {169 typ = termExact170 }171

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 172why, one step back
172 if len(set) > 0 && !afterBar && text == "|" {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

line 173why, one step back
173 switchSet = false

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 174why, one step back
174 afterBar = true

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 175–176why, one step back
175 continue
176 }

Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411

line 177why, one step back
177 afterBar = false

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 178–184why, one step back
178
179 if strings.HasPrefix(text, "!") {180 inv = true181 typ = termExact182 text = text[1:]183 }184

Treat $ as proper search queryJunegunn Choibefore adoption02a7b96

line 185why, one step back
185 if text != "$" && strings.HasSuffix(text, "$") {

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

lines 186–187why, one step back
186 typ = termSuffix
187 text = text[:len(text)-1]

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

lines 188–189why, one step back
188 }
189

Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c

line 190why, one step back
190 if strings.HasPrefix(text, "'") {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 191–199why, one step back
191 // Flip exactness
192 if fuzzy && !inv {193 typ = termExact194 text = text[1:]195 } else {196 typ = termFuzzy197 text = text[1:]198 }199 } else if strings.HasPrefix(text, "^") {

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 200why, one step back
200 if typ == termSuffix {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 201–204why, one step back
201 typ = termEqual
202 } else {203 typ = termPrefix204 }

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

lines 205–207why, one step back
205 text = text[1:]
206 }207

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 208–220why, one step back
208 if len(text) > 0 {
209 if switchSet {210 sets = append(sets, set)211 set = termSet{}212 }213 textRunes := []rune(text)214 if normalize {215 textRunes = algo.NormalizeRunes(textRunes)216 }217 set = append(set, term{218 typ: typ,219 inv: inv,220 text: textRunes,

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 221why, one step back
221 caseSensitive: caseSensitive})

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 222–243why, one step back
222 switchSet = true
223 }224 }225 if len(set) > 0 {226 sets = append(sets, set)227 }228 return sets229}230231// IsEmpty returns true if the pattern is effectively empty232func (p *Pattern) IsEmpty() bool {233 if !p.extended {234 return len(p.text) == 0235 }236 return len(p.termSets) == 0237}238239// AsString returns the search query in string type240func (p *Pattern) AsString() string {241 return string(p.text)242}243

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

line 244why, one step back
244func (p *Pattern) buildCacheKey() string {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 245–250why, one step back
245 if !p.extended {
246 return p.AsString()247 }248 cacheableTerms := []string{}249 for _, termSet := range p.termSets {250 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {

Fix invalid cache lookupsJunegunn Choibefore adoption999d374

line 251why, one step back
251 cacheableTerms = append(cacheableTerms, string(termSet[0].text))

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 252–253why, one step back
252 }
253 }

Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6

line 254why, one step back
254 return strings.Join(cacheableTerms, "\t")

Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029

lines 255–259why, one step back
255}
256257// CacheKey is used to build string to be used as the key of result cache258func (p *Pattern) CacheKey() string {259 return p.cacheKey

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 260–286why, one step back
260}
261262// Match returns the list of matches Items in the given Chunk263func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {264 // ChunkCache: Exact match265 cacheKey := p.CacheKey()266 if p.cacheable {267 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {268 return cached269 }270 }271272 // Prefix/suffix cache273 space := _cache.Search(chunk, cacheKey)274275 matches := p.matchChunk(chunk, space, slab)276277 if p.cacheable {278 _cache.Add(chunk, cacheKey, matches)279 }280 return matches281}282283func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {284 matches := []Result{}285286 if space == nil {

Remove special nilItemJunegunn Choibefore adoption0d171ba

lines 287–288why, one step back
287 for idx := 0; idx < chunk.count; idx++ {
288 if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 289–320why, one step back
289 matches = append(matches, *match)
290 }291 }292 } else {293 for _, result := range space {294 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {295 matches = append(matches, *match)296 }297 }298 }299 return matches300}301302// MatchItem returns true if the Item is a match303func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {304 if p.extended {305 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {306 result := buildResult(item, offsets, bonus)307 return &result, offsets, pos308 }309 return nil, nil, nil310 }311 offset, bonus, pos := p.basicMatch(item, withPos, slab)312 if sidx := offset[0]; sidx >= 0 {313 offsets := []Offset{offset}314 result := buildResult(item, offsets, bonus)315 return &result, offsets, pos316 }317 return nil, nil, nil318}319320func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {

Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa

lines 321–326why, one step back
321 var input []Token
322 if len(p.nth) == 0 {323 input = []Token{Token{text: &item.text, prefixLength: 0}}324 } else {325 input = p.transformInput(item)326 }

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 327–333why, one step back
327 if p.fuzzy {
328 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)329 }330 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)331}332333func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {

Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa

lines 334–339why, one step back
334 var input []Token
335 if len(p.nth) == 0 {336 input = []Token{Token{text: &item.text, prefixLength: 0}}337 } else {338 input = p.transformInput(item)339 }

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 340–382why, one step back
340 offsets := []Offset{}
341 var totalScore int342 var allPos *[]int343 if withPos {344 allPos = &[]int{}345 }346 for _, termSet := range p.termSets {347 var offset Offset348 var currentScore int349 matched := false350 for _, term := range termSet {351 pfun := p.procFun[term.typ]352 off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)353 if sidx := off[0]; sidx >= 0 {354 if term.inv {355 continue356 }357 offset, currentScore = off, score358 matched = true359 if withPos {360 if pos != nil {361 *allPos = append(*allPos, *pos...)362 } else {363 for idx := off[0]; idx < off[1]; idx++ {364 *allPos = append(*allPos, int(idx))365 }366 }367 }368 break369 } else if term.inv {370 offset, currentScore = Offset{0, 0}, 0371 matched = true372 continue373 }374 }375 if matched {376 offsets = append(offsets, offset)377 totalScore += currentScore378 }379 }380 return offsets, totalScore, allPos381}382

Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa

line 383why, one step back
383func (p *Pattern) transformInput(item *Item) []Token {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 384–387why, one step back
384 if item.transformed != nil {
385 return *item.transformed386 }387

Avoid unconditionally storsing input as runesJunegunn Choibefore adoptionc9f16b6

line 388why, one step back
388 tokens := Tokenize(item.text.ToString(), p.delimiter)

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 389–395why, one step back
389 ret := Transform(tokens, p.nth)
390 item.transformed = &ret391 return ret392}393394func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {395 for _, part := range tokens {

Pass util.Chars by pointerJunegunn Choibefore adoptiona2a4df0

line 396why, one step back
396 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {

Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4

lines 397–408why, one step back
397 sidx := int32(res.Start) + part.prefixLength
398 eidx := int32(res.End) + part.prefixLength399 if pos != nil {400 for idx := range *pos {401 (*pos)[idx] += int(part.prefixLength)402 }403 }404 return Offset{sidx, eidx}, res.Score, pos405 }406 }407 return Offset{-1, -1}, 0, nil408}