pattern.go
This file
Path
src/pattern.go
394 lines · 9.3 KiB · Go
Last changed by
Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
History of this fileTake it
The walk stopped after 200 commits: lines older than 14f0d20 point at it.
Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 1–37why, one step back1package fzf23import (4 "regexp"5 "strings"67 "github.com/junegunn/fzf/src/algo"8 "github.com/junegunn/fzf/src/util"9)1011// fuzzy12// 'exact13// ^exact-prefix14// exact-suffix$15// !not-fuzzy16// !'not-exact17// !^not-exact-prefix18// !not-exact-suffix$1920type termType int2122const (23 termFuzzy termType = iota24 termExact25 termPrefix26 termSuffix27 termEqual28)2930type term struct {31 typ termType32 inv bool33 text []rune34 caseSensitive bool35 origText []rune36}37Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 38–39why, one step back38type termSet []term39Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 40–42why, one step back40// Pattern represents search pattern41type Pattern struct {42 fuzzy boolRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 43why, one step back43 fuzzyAlgo algo.AlgoUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 44–47why, one step back44 extended bool45 caseSensitive bool46 forward bool47 text []runeAdd OR operatorJunegunn Choibefore adoptione7e86b6
lines 48–49why, one step back48 termSets []termSet49 cacheable boolUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 50–51why, one step back50 delimiter Delimiter51 nth []RangeRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 52why, one step back52 procFun map[termType]algo.AlgoUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 53–77why, one step back53}5455var (56 _patternCache map[string]*Pattern57 _splitRegex *regexp.Regexp58 _cache ChunkCache59)6061func init() {62 _splitRegex = regexp.MustCompile("\\s+")63 clearPatternCache()64 clearChunkCache()65}6667func clearPatternCache() {68 // We can uniquely identify the pattern for a given string since69 // search mode and caseMode do not change while the program is running70 _patternCache = make(map[string]*Pattern)71}7273func clearChunkCache() {74 _cache = NewChunkCache()75}7677// BuildPattern builds Pattern object from the given argumentsRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 78why, one step back78func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, forward bool,No need to cache the result in filtering mode (--filter)Junegunn Choibefore adoptionf8fdf96
line 79why, one step back79 cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 80–92why, one step back8081 var asString string82 if extended {83 asString = strings.Trim(string(runes), " ")84 } else {85 asString = string(runes)86 }8788 cached, found := _patternCache[asString]89 if found {90 return cached91 }92No need to cache the result in filtering mode (--filter)Junegunn Choibefore adoptionf8fdf96
line 93why, one step back93 caseSensitive := trueAdd OR operatorJunegunn Choibefore adoptione7e86b6
line 94why, one step back94 termSets := []termSet{}Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 95–96why, one step back9596 if extended {Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 97–102why, one step back97 termSets = parseTerms(fuzzy, caseMode, asString)98 Loop:99 for _, termSet := range termSets {100 for idx, term := range termSet {101 // If the query contains inverse search terms or OR operators,102 // we cannot cache the search scopeNo need to cache the result in filtering mode (--filter)Junegunn Choibefore adoptionf8fdf96
line 103why, one step back103 if !cacheable || idx > 0 || term.inv {Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 104–106why, one step back104 cacheable = false105 break Loop106 }Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 107–119why, one step back107 }108 }109 } else {110 lowerString := strings.ToLower(asString)111 caseSensitive = caseMode == CaseRespect ||112 caseMode == CaseSmart && lowerString != asString113 if !caseSensitive {114 asString = lowerString115 }116 }117118 ptr := &Pattern{119 fuzzy: fuzzy,Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 120why, one step back120 fuzzyAlgo: fuzzyAlgo,Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 121–124why, one step back121 extended: extended,122 caseSensitive: caseSensitive,123 forward: forward,124 text: []rune(asString),Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 125–126why, one step back125 termSets: termSets,126 cacheable: cacheable,Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 127–128why, one step back127 nth: nth,128 delimiter: delimiter,Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 129why, one step back129 procFun: make(map[termType]algo.Algo)}Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 130why, one step back130Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 131why, one step back131 ptr.procFun[termFuzzy] = fuzzyAlgoUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 132–140why, one step back132 ptr.procFun[termEqual] = algo.EqualMatch133 ptr.procFun[termExact] = algo.ExactMatchNaive134 ptr.procFun[termPrefix] = algo.PrefixMatch135 ptr.procFun[termSuffix] = algo.SuffixMatch136137 _patternCache[asString] = ptr138 return ptr139}140Add OR operatorJunegunn Choibefore adoptione7e86b6
line 141why, one step back141func parseTerms(fuzzy bool, caseMode Case, str string) []termSet {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 142why, one step back142 tokens := _splitRegex.Split(str, -1)Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 143–145why, one step back143 sets := []termSet{}144 set := termSet{}145 switchSet := falseUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 146–158why, one step back146 for _, token := range tokens {147 typ, inv, text := termFuzzy, false, token148 lowerText := strings.ToLower(text)149 caseSensitive := caseMode == CaseRespect ||150 caseMode == CaseSmart && text != lowerText151 if !caseSensitive {152 text = lowerText153 }154 origText := []rune(text)155 if !fuzzy {156 typ = termExact157 }158Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 159–163why, one step back159 if text == "|" {160 switchSet = false161 continue162 }163Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 164–191why, one step back164 if strings.HasPrefix(text, "!") {165 inv = true166 text = text[1:]167 }168169 if strings.HasPrefix(text, "'") {170 // Flip exactness171 if fuzzy {172 typ = termExact173 text = text[1:]174 } else {175 typ = termFuzzy176 text = text[1:]177 }178 } else if strings.HasPrefix(text, "^") {179 if strings.HasSuffix(text, "$") {180 typ = termEqual181 text = text[1 : len(text)-1]182 } else {183 typ = termPrefix184 text = text[1:]185 }186 } else if strings.HasSuffix(text, "$") {187 typ = termSuffix188 text = text[:len(text)-1]189 }190191 if len(text) > 0 {Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 192–196why, one step back192 if switchSet {193 sets = append(sets, set)194 set = termSet{}195 }196 set = append(set, term{Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 197–201why, one step back197 typ: typ,198 inv: inv,199 text: []rune(text),200 caseSensitive: caseSensitive,201 origText: origText})Add OR operatorJunegunn Choibefore adoptione7e86b6
line 202why, one step back202 switchSet = trueUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 203–204why, one step back203 }204 }Add OR operatorJunegunn Choibefore adoptione7e86b6
lines 205–208why, one step back205 if len(set) > 0 {206 sets = append(sets, set)207 }208 return setsUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 209–215why, one step back209}210211// IsEmpty returns true if the pattern is effectively empty212func (p *Pattern) IsEmpty() bool {213 if !p.extended {214 return len(p.text) == 0215 }Add OR operatorJunegunn Choibefore adoptione7e86b6
line 216why, one step back216 return len(p.termSets) == 0Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 217–229why, one step back217}218219// AsString returns the search query in string type220func (p *Pattern) AsString() string {221 return string(p.text)222}223224// CacheKey is used to build string to be used as the key of result cache225func (p *Pattern) CacheKey() string {226 if !p.extended {227 return p.AsString()228 }229 cacheableTerms := []string{}Add OR operatorJunegunn Choibefore adoptione7e86b6
line 230why, one step back230 for _, termSet := range p.termSets {Fix incorrect cache reference in --exact mode (#547)Junegunn Choibefore adoption85ef326
line 231why, one step back231 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {Add OR operatorJunegunn Choibefore adoptione7e86b6
line 232why, one step back232 cacheableTerms = append(cacheableTerms, string(termSet[0].origText))Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 233–238why, one step back233 }234 }235 return strings.Join(cacheableTerms, " ")236}237238// Match returns the list of matches Items in the given ChunkRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 239why, one step back239func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 240–241why, one step back240 // ChunkCache: Exact match241 cacheKey := p.CacheKey()Add OR operatorJunegunn Choibefore adoptione7e86b6
line 242why, one step back242 if p.cacheable {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 243–247why, one step back243 if cached, found := _cache.Find(chunk, cacheKey); found {244 return cached245 }246 }247Micro-optimizationsJunegunn Choibefore adoption37dc273
lines 248–249why, one step back248 // Prefix/suffix cache249 var space []*ResultUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 250–258why, one step back250Loop:251 for idx := 1; idx < len(cacheKey); idx++ {252 // [---------| ] | [ |---------]253 // [--------| ] | [ |--------]254 // [-------| ] | [ |-------]255 prefix := cacheKey[:len(cacheKey)-idx]256 suffix := cacheKey[idx:]257 for _, substr := range [2]*string{&prefix, &suffix} {258 if cached, found := _cache.Find(chunk, *substr); found {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 259why, one step back259 space = cachedUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 260–264why, one step back260 break Loop261 }262 }263 }264Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 265why, one step back265 matches := p.matchChunk(chunk, space, slab)Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 266why, one step back266Add OR operatorJunegunn Choibefore adoptione7e86b6
line 267why, one step back267 if p.cacheable {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 268–272why, one step back268 _cache.Add(chunk, cacheKey, matches)269 }270 return matches271}272Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 273why, one step back273func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {Micro-optimizationsJunegunn Choibefore adoption37dc273
lines 274–276why, one step back274 matches := []*Result{}275276 if space == nil {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 277why, one step back277 for _, item := range *chunk {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 278why, one step back278 if match, _, _ := p.MatchItem(item, false, slab); match != nil {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 279why, one step back279 matches = append(matches, match)Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 280–282why, one step back280 }281 }282 } else {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 283why, one step back283 for _, result := range space {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 284why, one step back284 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 285why, one step back285 matches = append(matches, match)Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 286–292why, one step back286 }287 }288 }289 return matches290}291292// MatchItem returns true if the Item is a matchRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 293why, one step back293func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 294why, one step back294 if p.extended {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
lines 295–296why, one step back295 if offsets, bonus, trimLen, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {296 return buildResult(item, offsets, bonus, trimLen), offsets, posMicro-optimizationsJunegunn Choibefore adoption37dc273
line 297why, one step back297 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 298why, one step back298 return nil, nil, nilUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 299why, one step back299 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 300why, one step back300 offset, bonus, trimLen, pos := p.basicMatch(item, withPos, slab)Micro-optimizationsJunegunn Choibefore adoption37dc273
line 301why, one step back301 if sidx := offset[0]; sidx >= 0 {Remove Offset slice from Result structJunegunn Choibefore adoption827a83e
line 302why, one step back302 offsets := []Offset{offset}Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 303why, one step back303 return buildResult(item, offsets, bonus, trimLen), offsets, posMicro-optimizationsJunegunn Choibefore adoption37dc273
line 304why, one step back304 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 305why, one step back305 return nil, nil, nilUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 306–307why, one step back306}307Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 308why, one step back308func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 309–310why, one step back309 input := p.prepareInput(item)310 if p.fuzzy {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 311why, one step back311 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.forward, p.text, withPos, slab)Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 312why, one step back312 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 313why, one step back313 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.forward, p.text, withPos, slab)Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 314–315why, one step back314}315Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 316why, one step back316func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, int, *[]int) {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 317–318why, one step back317 input := p.prepareInput(item)318 offsets := []Offset{}Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 319why, one step back319 var totalScore intMicro-optimizationsJunegunn Choibefore adoption37dc273
line 320why, one step back320 var totalTrimLen intRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
lines 321–324why, one step back321 var allPos *[]int322 if withPos {323 allPos = &[]int{}324 }Add OR operatorJunegunn Choibefore adoptione7e86b6
line 325why, one step back325 for _, termSet := range p.termSets {Micro-optimizationsJunegunn Choibefore adoption37dc273
line 326why, one step back326 var offset OffsetRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 327why, one step back327 var currentScore intMicro-optimizationsJunegunn Choibefore adoption37dc273
lines 328–329why, one step back328 var trimLen int329 matched := falseAdd OR operatorJunegunn Choibefore adoptione7e86b6
lines 330–331why, one step back330 for _, term := range termSet {331 pfun := p.procFun[term.typ]Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 332why, one step back332 off, score, tLen, pos := p.iter(pfun, input, term.caseSensitive, p.forward, term.text, withPos, slab)Enhanced ranking algorithmJunegunn Choibefore adoption2f6d23b
line 333why, one step back333 if sidx := off[0]; sidx >= 0 {Add OR operatorJunegunn Choibefore adoptione7e86b6
line 334why, one step back334 if term.inv {Fix compatibility issues with OR operator and inverse termsJunegunn Choibefore adoption31278bc
line 335why, one step back335 continueAdd OR operatorJunegunn Choibefore adoptione7e86b6
line 336why, one step back336 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 337why, one step back337 offset, currentScore, trimLen = off, score, tLenMicro-optimizationsJunegunn Choibefore adoption37dc273
line 338why, one step back338 matched = trueRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
lines 339–347why, one step back339 if withPos {340 if pos != nil {341 *allPos = append(*allPos, *pos...)342 } else {343 for idx := off[0]; idx < off[1]; idx++ {344 *allPos = append(*allPos, int(idx))345 }346 }347 }Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 348why, one step back348 breakAdd OR operatorJunegunn Choibefore adoptione7e86b6
line 349why, one step back349 } else if term.inv {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 350why, one step back350 offset, currentScore, trimLen = Offset{0, 0}, 0, 0Micro-optimizationsJunegunn Choibefore adoption37dc273
line 351why, one step back351 matched = trueFix compatibility issues with OR operator and inverse termsJunegunn Choibefore adoption31278bc
line 352why, one step back352 continueUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 353why, one step back353 }Fix compatibility issues with OR operator and inverse termsJunegunn Choibefore adoption31278bc
line 354why, one step back354 }Micro-optimizationsJunegunn Choibefore adoption37dc273
lines 355–356why, one step back355 if matched {356 offsets = append(offsets, offset)Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 357why, one step back357 totalScore += currentScoreMicro-optimizationsJunegunn Choibefore adoption37dc273
line 358why, one step back358 totalTrimLen += trimLenUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 359–360why, one step back359 }360 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 361why, one step back361 return offsets, totalScore, totalTrimLen, allPosUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 362–369why, one step back362}363364func (p *Pattern) prepareInput(item *Item) []Token {365 if item.transformed != nil {366 return item.transformed367 }368369 var ret []TokenMicro-optimizationsJunegunn Choibefore adoption37dc273
lines 370–372why, one step back370 if len(p.nth) == 0 {371 ret = []Token{Token{text: &item.text, prefixLength: 0, trimLength: int32(item.text.TrimLength())}}372 } else {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 373–379why, one step back373 tokens := Tokenize(item.text, p.delimiter)374 ret = Transform(tokens, p.nth)375 }376 item.transformed = ret377 return ret378}379Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 380why, one step back380func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, int, *[]int) {Update Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 381why, one step back381 for _, part := range tokens {Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 382why, one step back382 if res, pos := pfun(caseSensitive, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {Micro-optimizationsJunegunn Choibefore adoption37dc273
lines 383–384why, one step back383 sidx := int32(res.Start) + part.prefixLength384 eidx := int32(res.End) + part.prefixLengthRevise ranking algorithmJunegunn Choibefore adoption2fc7c18
lines 385–390why, one step back385 if pos != nil {386 for idx := range *pos {387 (*pos)[idx] += int(part.prefixLength)388 }389 }390 return Offset{sidx, eidx}, res.Score, int(part.trimLength), posUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
lines 391–392why, one step back391 }392 }Revise ranking algorithmJunegunn Choibefore adoption2fc7c18
line 393why, one step back393 return Offset{-1, -1}, 0, -1, nilUpdate Homebrew instructionsJunegunn Choibefore adoption14f0d20
line 394why, one step back394}