pattern.go
This file
Path
src/pattern.go
423 lines · 10.5 KiB · Go
Last changed by
Implement exact-boundary match typeJunegunn Choibefore adoption6a67712
History of this fileTake it
The walk stopped after 200 commits: lines older than 4bedd33 point at it.
Refactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 1–25why, one step back1package fzf23import (4 "fmt"5 "regexp"6 "strings"78 "github.com/junegunn/fzf/src/algo"9 "github.com/junegunn/fzf/src/util"10)1112// fuzzy13// 'exact14// ^prefix-exact15// suffix-exact$16// !inverse-exact17// !'inverse-fuzzy18// !^inverse-prefix-exact19// !inverse-suffix-exact$2021type termType int2223const (24 termFuzzy termType = iota25 termExactImplement exact-boundary match typeJunegunn Choibefore adoption6a67712
line 26why, one step back26 termExactBoundaryRefactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 27–150why, one step back27 termPrefix28 termSuffix29 termEqual30)3132type term struct {33 typ termType34 inv bool35 text []rune36 caseSensitive bool37 normalize bool38}3940// String returns the string representation of a term.41func (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}4445type termSet []term4647// Pattern represents search pattern48type Pattern struct {49 fuzzy bool50 fuzzyAlgo algo.Algo51 extended bool52 caseSensitive bool53 normalize bool54 forward bool55 withPos bool56 text []rune57 termSets []termSet58 sortable bool59 cacheable bool60 cacheKey string61 delimiter Delimiter62 nth []Range63 procFun map[termType]algo.Algo64 cache *ChunkCache65}6667var _splitRegex *regexp.Regexp6869func init() {70 _splitRegex = regexp.MustCompile(" +")71}7273// BuildPattern builds Pattern object from the given arguments74func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,75 withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {7677 var asString string78 if extended {79 asString = strings.TrimLeft(string(runes), " ")80 for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {81 asString = asString[:len(asString)-1]82 }83 } else {84 asString = string(runes)85 }8687 // We can uniquely identify the pattern for a given string since88 // search mode and caseMode do not change while the program is running89 cached, found := patternCache[asString]90 if found {91 return cached92 }9394 caseSensitive := true95 sortable := true96 termSets := []termSet{}9798 if extended {99 termSets = parseTerms(fuzzy, caseMode, normalize, asString)100 // We should not sort the result if there are only inverse search terms101 sortable = false102 Loop:103 for _, termSet := range termSets {104 for idx, term := range termSet {105 if !term.inv {106 sortable = true107 }108 // If the query contains inverse search terms or OR operators,109 // we cannot cache the search scope110 if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {111 cacheable = false112 if sortable {113 // Can't break until we see at least one non-inverse term114 break Loop115 }116 }117 }118 }119 } else {120 lowerString := strings.ToLower(asString)121 normalize = normalize &&122 lowerString == string(algo.NormalizeRunes([]rune(lowerString)))123 caseSensitive = caseMode == CaseRespect ||124 caseMode == CaseSmart && lowerString != asString125 if !caseSensitive {126 asString = lowerString127 }128 }129130 ptr := &Pattern{131 fuzzy: fuzzy,132 fuzzyAlgo: fuzzyAlgo,133 extended: extended,134 caseSensitive: caseSensitive,135 normalize: normalize,136 forward: forward,137 withPos: withPos,138 text: []rune(asString),139 termSets: termSets,140 sortable: sortable,141 cacheable: cacheable,142 nth: nth,143 delimiter: delimiter,144 cache: cache,145 procFun: make(map[termType]algo.Algo)}146147 ptr.cacheKey = ptr.buildCacheKey()148 ptr.procFun[termFuzzy] = fuzzyAlgo149 ptr.procFun[termEqual] = algo.EqualMatch150 ptr.procFun[termExact] = algo.ExactMatchNaiveImplement exact-boundary match typeJunegunn Choibefore adoption6a67712
line 151why, one step back151 ptr.procFun[termExactBoundary] = algo.ExactMatchBoundaryRefactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 152–159why, one step back152 ptr.procFun[termPrefix] = algo.PrefixMatch153 ptr.procFun[termSuffix] = algo.SuffixMatch154155 patternCache[asString] = ptr156 return ptr157}158159func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {chore: use strings.ReplaceAll (#3801)Zhizhen Hebefore adoption01e7668
line 160why, one step back160 str = strings.ReplaceAll(str, "\\ ", "\t")Refactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 161–166why, one step back161 tokens := _splitRegex.Split(str, -1)162 sets := []termSet{}163 set := termSet{}164 switchSet := false165 afterBar := false166 for _, token := range tokens {chore: use strings.ReplaceAll (#3801)Zhizhen Hebefore adoption01e7668
line 167why, one step back167 typ, inv, text := termFuzzy, false, strings.ReplaceAll(token, "\t", " ")Refactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 168–197why, one step back168 lowerText := strings.ToLower(text)169 caseSensitive := caseMode == CaseRespect ||170 caseMode == CaseSmart && text != lowerText171 normalizeTerm := normalize &&172 lowerText == string(algo.NormalizeRunes([]rune(lowerText)))173 if !caseSensitive {174 text = lowerText175 }176 if !fuzzy {177 typ = termExact178 }179180 if len(set) > 0 && !afterBar && text == "|" {181 switchSet = false182 afterBar = true183 continue184 }185 afterBar = false186187 if strings.HasPrefix(text, "!") {188 inv = true189 typ = termExact190 text = text[1:]191 }192193 if text != "$" && strings.HasSuffix(text, "$") {194 typ = termSuffix195 text = text[:len(text)-1]196 }197Implement exact-boundary match typeJunegunn Choibefore adoption6a67712
lines 198–205why, one step back198 if fuzzy && len(text) > 2 && strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") ||199 !fuzzy && !strings.HasPrefix(text, "'") && strings.HasSuffix(text, "'") {200 typ = termExactBoundary201 if fuzzy {202 text = text[1:]203 }204 text = text[:len(text)-1]205 } else if strings.HasPrefix(text, "'") {Refactor the code to remove global variablesJunegunn Choibefore adoption4bedd33
lines 206–423why, one step back206 // Flip exactness207 if fuzzy && !inv {208 typ = termExact209 } else {210 typ = termFuzzy211 }212 text = text[1:]213 } else if strings.HasPrefix(text, "^") {214 if typ == termSuffix {215 typ = termEqual216 } else {217 typ = termPrefix218 }219 text = text[1:]220 }221222 if len(text) > 0 {223 if switchSet {224 sets = append(sets, set)225 set = termSet{}226 }227 textRunes := []rune(text)228 if normalizeTerm {229 textRunes = algo.NormalizeRunes(textRunes)230 }231 set = append(set, term{232 typ: typ,233 inv: inv,234 text: textRunes,235 caseSensitive: caseSensitive,236 normalize: normalizeTerm})237 switchSet = true238 }239 }240 if len(set) > 0 {241 sets = append(sets, set)242 }243 return sets244}245246// IsEmpty returns true if the pattern is effectively empty247func (p *Pattern) IsEmpty() bool {248 if !p.extended {249 return len(p.text) == 0250 }251 return len(p.termSets) == 0252}253254// AsString returns the search query in string type255func (p *Pattern) AsString() string {256 return string(p.text)257}258259func (p *Pattern) buildCacheKey() string {260 if !p.extended {261 return p.AsString()262 }263 cacheableTerms := []string{}264 for _, termSet := range p.termSets {265 if len(termSet) == 1 && !termSet[0].inv && (p.fuzzy || termSet[0].typ == termExact) {266 cacheableTerms = append(cacheableTerms, string(termSet[0].text))267 }268 }269 return strings.Join(cacheableTerms, "\t")270}271272// CacheKey is used to build string to be used as the key of result cache273func (p *Pattern) CacheKey() string {274 return p.cacheKey275}276277// Match returns the list of matches Items in the given Chunk278func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {279 // ChunkCache: Exact match280 cacheKey := p.CacheKey()281 if p.cacheable {282 if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {283 return cached284 }285 }286287 // Prefix/suffix cache288 space := p.cache.Search(chunk, cacheKey)289290 matches := p.matchChunk(chunk, space, slab)291292 if p.cacheable {293 p.cache.Add(chunk, cacheKey, matches)294 }295 return matches296}297298func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {299 matches := []Result{}300301 if space == nil {302 for idx := 0; idx < chunk.count; idx++ {303 if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match != nil {304 matches = append(matches, *match)305 }306 }307 } else {308 for _, result := range space {309 if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match != nil {310 matches = append(matches, *match)311 }312 }313 }314 return matches315}316317// MatchItem returns true if the Item is a match318func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {319 if p.extended {320 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {321 result := buildResult(item, offsets, bonus)322 return &result, offsets, pos323 }324 return nil, nil, nil325 }326 offset, bonus, pos := p.basicMatch(item, withPos, slab)327 if sidx := offset[0]; sidx >= 0 {328 offsets := []Offset{offset}329 result := buildResult(item, offsets, bonus)330 return &result, offsets, pos331 }332 return nil, nil, nil333}334335func (p *Pattern) basicMatch(item *Item, withPos bool, slab *util.Slab) (Offset, int, *[]int) {336 var input []Token337 if len(p.nth) == 0 {338 input = []Token{{text: &item.text, prefixLength: 0}}339 } else {340 input = p.transformInput(item)341 }342 if p.fuzzy {343 return p.iter(p.fuzzyAlgo, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)344 }345 return p.iter(algo.ExactMatchNaive, input, p.caseSensitive, p.normalize, p.forward, p.text, withPos, slab)346}347348func (p *Pattern) extendedMatch(item *Item, withPos bool, slab *util.Slab) ([]Offset, int, *[]int) {349 var input []Token350 if len(p.nth) == 0 {351 input = []Token{{text: &item.text, prefixLength: 0}}352 } else {353 input = p.transformInput(item)354 }355 offsets := []Offset{}356 var totalScore int357 var allPos *[]int358 if withPos {359 allPos = &[]int{}360 }361 for _, termSet := range p.termSets {362 var offset Offset363 var currentScore int364 matched := false365 for _, term := range termSet {366 pfun := p.procFun[term.typ]367 off, score, pos := p.iter(pfun, input, term.caseSensitive, term.normalize, p.forward, term.text, withPos, slab)368 if sidx := off[0]; sidx >= 0 {369 if term.inv {370 continue371 }372 offset, currentScore = off, score373 matched = true374 if withPos {375 if pos != nil {376 *allPos = append(*allPos, *pos...)377 } else {378 for idx := off[0]; idx < off[1]; idx++ {379 *allPos = append(*allPos, int(idx))380 }381 }382 }383 break384 } else if term.inv {385 offset, currentScore = Offset{0, 0}, 0386 matched = true387 continue388 }389 }390 if matched {391 offsets = append(offsets, offset)392 totalScore += currentScore393 }394 }395 return offsets, totalScore, allPos396}397398func (p *Pattern) transformInput(item *Item) []Token {399 if item.transformed != nil {400 return *item.transformed401 }402403 tokens := Tokenize(item.text.ToString(), p.delimiter)404 ret := Transform(tokens, p.nth)405 item.transformed = &ret406 return ret407}408409func (p *Pattern) iter(pfun algo.Algo, tokens []Token, caseSensitive bool, normalize bool, forward bool, pattern []rune, withPos bool, slab *util.Slab) (Offset, int, *[]int) {410 for _, part := range tokens {411 if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {412 sidx := int32(res.Start) + part.prefixLength413 eidx := int32(res.End) + part.prefixLength414 if pos != nil {415 for idx := range *pos {416 (*pos)[idx] += int(part.prefixLength)417 }418 }419 return Offset{sidx, eidx}, res.Score, pos420 }421 }422 return Offset{-1, -1}, 0, nil423}