pattern.go
This file
Path
src/pattern.go
391 lines · 9.2 KiB · Go
Last changed by
Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
History of this fileTake it
The walk stopped after 200 commits: lines older than de1c6b8 point at it.
[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 1–45why, 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}3738type termSet []term3940// Pattern represents search pattern41type Pattern struct {42 fuzzy bool43 fuzzyAlgo algo.Algo44 extended bool45 caseSensitive boolMerge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 46why, one step back46 normalize bool[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 47–78why, one step back47 forward bool48 text []rune49 termSets []termSet50 cacheable bool51 delimiter Delimiter52 nth []Range53 procFun map[termType]algo.Algo54}5556var (57 _patternCache map[string]*Pattern58 _splitRegex *regexp.Regexp59 _cache ChunkCache60)6162func init() {63 _splitRegex = regexp.MustCompile("\\s+")64 clearPatternCache()65 clearChunkCache()66}6768func clearPatternCache() {69 // We can uniquely identify the pattern for a given string since70 // search mode and caseMode do not change while the program is running71 _patternCache = make(map[string]*Pattern)72}7374func clearChunkCache() {75 _cache = NewChunkCache()76}7778// BuildPattern builds Pattern object from the given argumentsMerge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 79why, one step back79func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 80–97why, one step back80 cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {8182 var asString string83 if extended {84 asString = strings.Trim(string(runes), " ")85 } else {86 asString = string(runes)87 }8889 cached, found := _patternCache[asString]90 if found {91 return cached92 }9394 caseSensitive := true95 termSets := []termSet{}9697 if extended {Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 98why, one step back98 termSets = parseTerms(fuzzy, caseMode, normalize, asString)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 99–103why, one step back99 Loop:100 for _, termSet := range termSets {101 for idx, term := range termSet {102 // If the query contains inverse search terms or OR operators,103 // we cannot cache the search scopeFix caching scheme when --exact is set and '-prefix is usedJunegunn Choibefore adoptiondd1f265
line 104why, one step back104 if !cacheable || idx > 0 || term.inv || !fuzzy && term.typ != termExact {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 105–123why, one step back105 cacheable = false106 break Loop107 }108 }109 }110 } else {111 lowerString := strings.ToLower(asString)112 caseSensitive = caseMode == CaseRespect ||113 caseMode == CaseSmart && lowerString != asString114 if !caseSensitive {115 asString = lowerString116 }117 }118119 ptr := &Pattern{120 fuzzy: fuzzy,121 fuzzyAlgo: fuzzyAlgo,122 extended: extended,123 caseSensitive: caseSensitive,Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 124why, one step back124 normalize: normalize,[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 125–142why, one step back125 forward: forward,126 text: []rune(asString),127 termSets: termSets,128 cacheable: cacheable,129 nth: nth,130 delimiter: delimiter,131 procFun: make(map[termType]algo.Algo)}132133 ptr.procFun[termFuzzy] = fuzzyAlgo134 ptr.procFun[termEqual] = algo.EqualMatch135 ptr.procFun[termExact] = algo.ExactMatchNaive136 ptr.procFun[termPrefix] = algo.PrefixMatch137 ptr.procFun[termSuffix] = algo.SuffixMatch138139 _patternCache[asString] = ptr140 return ptr141}142Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 143why, one step back143func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 144–198why, one step back144 tokens := _splitRegex.Split(str, -1)145 sets := []termSet{}146 set := termSet{}147 switchSet := false148 for _, token := range tokens {149 typ, inv, text := termFuzzy, false, token150 lowerText := strings.ToLower(text)151 caseSensitive := caseMode == CaseRespect ||152 caseMode == CaseSmart && text != lowerText153 if !caseSensitive {154 text = lowerText155 }156 origText := []rune(text)157 if !fuzzy {158 typ = termExact159 }160161 if text == "|" {162 switchSet = false163 continue164 }165166 if strings.HasPrefix(text, "!") {167 inv = true168 typ = termExact169 text = text[1:]170 }171172 if strings.HasPrefix(text, "'") {173 // Flip exactness174 if fuzzy && !inv {175 typ = termExact176 text = text[1:]177 } else {178 typ = termFuzzy179 text = text[1:]180 }181 } else if strings.HasPrefix(text, "^") {182 if strings.HasSuffix(text, "$") {183 typ = termEqual184 text = text[1 : len(text)-1]185 } else {186 typ = termPrefix187 text = text[1:]188 }189 } else if strings.HasSuffix(text, "$") {190 typ = termSuffix191 text = text[:len(text)-1]192 }193194 if len(text) > 0 {195 if switchSet {196 sets = append(sets, set)197 set = termSet{}198 }Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
lines 199–202why, one step back199 textRunes := []rune(text)200 if normalize {201 textRunes = algo.NormalizeRunes(textRunes)202 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 203–205why, one step back203 set = append(set, term{204 typ: typ,205 inv: inv,Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 206why, one step back206 text: textRunes,[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 207–245why, one step back207 caseSensitive: caseSensitive,208 origText: origText})209 switchSet = true210 }211 }212 if len(set) > 0 {213 sets = append(sets, set)214 }215 return sets216}217218// IsEmpty returns true if the pattern is effectively empty219func (p *Pattern) IsEmpty() bool {220 if !p.extended {221 return len(p.text) == 0222 }223 return len(p.termSets) == 0224}225226// AsString returns the search query in string type227func (p *Pattern) AsString() string {228 return string(p.text)229}230231// CacheKey is used to build string to be used as the key of result cache232func (p *Pattern) CacheKey() string {233 if !p.extended {234 return p.AsString()235 }236 cacheableTerms := []string{}237 for _, termSet := range p.termSets {238 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {239 cacheableTerms = append(cacheableTerms, string(termSet[0].origText))240 }241 }242 return strings.Join(cacheableTerms, " ")243}244245// Match returns the list of matches Items in the given ChunkConsolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 246why, one step back246func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 247–249why, one step back247 // ChunkCache: Exact match248 cacheKey := p.CacheKey()249 if p.cacheable {Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
line 250why, one step back250 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 251–255why, one step back251 return cached252 }253 }254255 // Prefix/suffix cacheRefactor cache lookupJunegunn Choibefore adoption8dbdd55
line 256why, one step back256 space := _cache.Search(chunk, cacheKey)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 257–265why, one step back257258 matches := p.matchChunk(chunk, space, slab)259260 if p.cacheable {261 _cache.Add(chunk, cacheKey, matches)262 }263 return matches264}265Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 266–267why, one step back266func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {267 matches := []Result{}[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 268–269why, one step back268269 if space == nil {Remove pointer indirection by changing Chunk definitionJunegunn Choibefore adoptiond4f3d5a
lines 270–271why, one step back270 for idx := range *chunk {271 if match, _, _ := p.MatchItem(&(*chunk)[idx], false, slab); match != nil {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 272why, one step back272 matches = append(matches, *match)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 273–277why, one step back273 }274 }275 } else {276 for _, result := range space {277 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
line 278why, one step back278 matches = append(matches, *match)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 279–287why, one step back279 }280 }281 }282 return matches283}284285// MatchItem returns true if the Item is a match286func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {287 if p.extended {Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 288why, one step back288 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 289–290why, one step back289 result := buildResult(item, offsets, bonus)290 return &result, offsets, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 291–293why, one step back291 }292 return nil, nil, nil293 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 294why, one step back294 offset, bonus, pos := p.basicMatch(item, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 295–296why, one step back295 if sidx := offset[0]; sidx >= 0 {296 offsets := []Offset{offset}Consolidate Result and rank structsJunegunn Choibefore adoptionbbe10f4
lines 297–298why, one step back297 result := buildResult(item, offsets, bonus)298 return &result, offsets, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 299–302why, one step back299 }300 return nil, nil, nil301}302Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 303why, one step back303func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
lines 304–309why, one step back304 var input []Token305 if len(p.nth) == 0 {306 input = []Token{Token{text: &item.text, prefixLength: 0}}307 } else {308 input = p.transformInput(item)309 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 310why, one step back310 if p.fuzzy {Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 311why, one step back311 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 312why, one step back312 }Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 313why, one step back313 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 314–315why, one step back314}315Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 316why, one step back316func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
lines 317–322why, one step back317 var input []Token318 if len(p.nth) == 0 {319 input = []Token{Token{text: &item.text, prefixLength: 0}}320 } else {321 input = p.transformInput(item)322 }[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 323–334why, one step back323 offsets := []Offset{}324 var totalScore int325 var allPos *[]int326 if withPos {327 allPos = &[]int{}328 }329 for _, termSet := range p.termSets {330 var offset Offset331 var currentScore int332 matched := false333 for _, term := range termSet {334 pfun := p.procFun[term.typ]Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 335why, one step back335 off, score, pos := p.iter(pfun, input, term.caseSensitive, p.normalize, p.forward, term.text, withPos, slab)[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 336–339why, one step back336 if sidx := off[0]; sidx >= 0 {337 if term.inv {338 continue339 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 340why, one step back340 offset, currentScore = off, score[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 341–352why, one step back341 matched = true342 if withPos {343 if pos != nil {344 *allPos = append(*allPos, *pos...)345 } else {346 for idx := off[0]; idx < off[1]; idx++ {347 *allPos = append(*allPos, int(idx))348 }349 }350 }351 break352 } else if term.inv {Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 353why, one step back353 offset, currentScore = Offset{0, 0}, 0[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 354–362why, one step back354 matched = true355 continue356 }357 }358 if matched {359 offsets = append(offsets, offset)360 totalScore += currentScore361 }362 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 363why, one step back363 return offsets, totalScore, allPos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 364–365why, one step back364}365Inline function calls in a tight loopJunegunn Choibefore adoptionf4b46fa
line 366why, one step back366func (p *Pattern) transformInput(item *Item) []Token {Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
lines 367–368why, one step back367 if item.transformed != nil {368 return *item.transformed[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 369why, one step back369 }Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
line 370why, one step back370Avoid unconditionally storsing input as runesJunegunn Choibefore adoptionc9f16b6
line 371why, one step back371 tokens := Tokenize(item.text.ToString(), p.delimiter)Reduce memory footprint of Item structJunegunn Choibefore adoption9e85cba
lines 372–373why, one step back372 ret := Transform(tokens, p.nth)373 item.transformed = &ret[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 374–376why, one step back374 return ret375}376Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 377why, one step back377func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 378why, one step back378 for _, part := range tokens {Merge pull request #794 from junegunn/develJunegunn Choibefore adoption05ed57a
line 379why, one step back379 if res, pos := pfun(caseSensitive, normalize, forward, *part.text, pattern, withPos, slab); res.Start >= 0 {[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 380–386why, one step back380 sidx := int32(res.Start) + part.prefixLength381 eidx := int32(res.End) + part.prefixLength382 if pos != nil {383 for idx := range *pos {384 (*pos)[idx] += int(part.prefixLength)385 }386 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 387why, one step back387 return Offset{sidx, eidx}, res.Score, pos[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
lines 388–389why, one step back388 }389 }Fix inconsistent tiebreak scores when --nth is usedJunegunn Choibefore adoption2e3dc75
line 390why, one step back390 return Offset{-1, -1}, 0, nil[tcell] 24-bit color supportJunegunn Choibefore adoptionde1c6b8
line 391why, one step back391}