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 fileTake 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 back1package fzf23import (Make fzf pass go vetRyan Boehningbefore adoption21b94d2
line 4why, one step back4 "fmt"Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 5–13why, one step back5 "regexp"6 "strings"78 "github.com/junegunn/fzf/src/algo"9 "github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exactFix invalid cache lookupsJunegunn Choibefore adoption999d374
lines 14–19why, one step back14// ^prefix-exact15// 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 back2021type termType int2223const (24 termFuzzy termType = iota25 termExact26 termPrefix27 termSuffix28 termEqual29)3031type term struct {32 typ termType33 inv bool34 text []rune35 caseSensitive boolMake fzf pass go vetRyan Boehningbefore adoption21b94d2
lines 36–40why, one step back36}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 back41}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 boolBuild cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 56why, one step back56 cacheKey stringConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 57–62why, one step back57 delimiter Delimiter58 nth []Range59 procFun map[termType]algo.Algo60}6162var (Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
lines 63–65why, one step back63 _patternCache map[string]*Pattern64 _splitRegex *regexp.Regexp65 _cache ChunkCacheConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 66–68why, one step back66)6768func init() {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 69why, one step back69 _splitRegex = regexp.MustCompile(" +")Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 70–89why, one step back70 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 back90 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 back94 } 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 scopeFix invalid cache lookupsJunegunn Choibefore adoption999d374
line 113why, one step back113 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 back114 cacheable = false115 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)}141Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 142why, one step back142 ptr.cacheKey = ptr.buildCacheKey()Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 143–153why, one step back143 ptr.procFun[termFuzzy] = fuzzyAlgo144 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 back154 str = strings.Replace(str, "\\ ", "\t", -1)Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 155–158why, one step back155 tokens := _splitRegex.Split(str, -1)156 sets := []termSet{}157 set := termSet{}158 switchSet := falseTreat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 159why, one step back159 afterBar := falseConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 160why, one step back160 for _, token := range tokens {Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 161why, one step back161 typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 162–171why, one step back162 lowerText := strings.ToLower(text)163 caseSensitive := caseMode == CaseRespect ||164 caseMode == CaseSmart && text != lowerText165 if !caseSensitive {166 text = lowerText167 }168 if !fuzzy {169 typ = termExact170 }171Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 172why, one step back172 if len(set) > 0 && !afterBar && text == "|" {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 173why, one step back173 switchSet = falseTreat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 174why, one step back174 afterBar = trueConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 175–176why, one step back175 continue176 }Treat | as proper query when it can't be an OR operatorJunegunn Choibefore adoptiona09e411
line 177why, one step back177 afterBar = falseConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 178–184why, one step back178179 if strings.HasPrefix(text, "!") {180 inv = true181 typ = termExact182 text = text[1:]183 }184Treat $ as proper search queryJunegunn Choibefore adoption02a7b96
line 185why, one step back185 if text != "$" && strings.HasSuffix(text, "$") {Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
lines 186–187why, one step back186 typ = termSuffix187 text = text[:len(text)-1]Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
lines 188–189why, one step back188 }189Disallow escaping of meta characters except for spacesJunegunn Choibefore adoption6c76d8c
line 190why, one step back190 if strings.HasPrefix(text, "'") {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 191–199why, one step back191 // Flip exactness192 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 back200 if typ == termSuffix {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 201–204why, one step back201 typ = termEqual202 } else {203 typ = termPrefix204 }Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
lines 205–207why, one step back205 text = text[1:]206 }207Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 208–220why, one step back208 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 back221 caseSensitive: caseSensitive})Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 222–243why, one step back222 switchSet = true223 }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}243Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
line 244why, one step back244func (p *Pattern) buildCacheKey() string {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 245–250why, one step back245 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 back251 cacheableTerms = append(cacheableTerms, string(termSet[0].text))Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 252–253why, one step back252 }253 }Allow escaping meta characters with backslashesJunegunn Choibefore adoptione85a8a6
line 254why, one step back254 return strings.Join(cacheableTerms, "\t")Build cache key for a pattern only onceJunegunn Choibefore adoptione55e029
lines 255–259why, one step back255}256257// CacheKey is used to build string to be used as the key of result cache258func (p *Pattern) CacheKey() string {259 return p.cacheKeyConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 260–286why, one step back260}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 back287 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 back289 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 back321 var input []Token322 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 back327 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 back334 var input []Token335 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 back340 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}382Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
line 383why, one step back383func (p *Pattern) transformInput(item *Item) []Token {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 384–387why, one step back384 if item.transformed != nil {385 return *item.transformed386 }387Avoid unconditionally storsing input as runesJunegunn Choibefore adoptionc9f16b6
line 388why, one step back388 tokens := Tokenize(item.text.ToString(), p.delimiter)Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 389–395why, one step back389 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 back396 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 back397 sidx := int32(res.Start) + part.prefixLength398 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}