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

1package 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	termExact26	termPrefix27	termSuffix28	termEqual29)3031type term struct {32	typ           termType33	inv           bool34	text          []rune35	caseSensitive bool36}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)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     bool56	cacheKey      string57	delimiter     Delimiter58	nth           []Range59	procFun       map[termType]algo.Algo60}6162var (63	_patternCache map[string]*Pattern64	_splitRegex   *regexp.Regexp65	_cache        ChunkCache66)6768func init() {69	_splitRegex = regexp.MustCompile(" +")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 {90		asString = strings.TrimLeft(string(runes), " ")91		for strings.HasSuffix(asString, " ") && !strings.HasSuffix(asString, "\\ ") {92			asString = asString[:len(asString)-1]93		}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 scope113				if !cacheable || idx > 0 || term.inv || fuzzy && term.typ != termFuzzy || !fuzzy && term.typ != termExact {114					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)}141142	ptr.cacheKey = ptr.buildCacheKey()143	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 {154	str = strings.Replace(str, "\\ ", "\t", -1)155	tokens := _splitRegex.Split(str, -1)156	sets := []termSet{}157	set := termSet{}158	switchSet := false159	afterBar := false160	for _, token := range tokens {161		typ, inv, text := termFuzzy, false, strings.Replace(token, "\t", " ", -1)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		}171172		if len(set) > 0 && !afterBar && text == "|" {173			switchSet = false174			afterBar = true175			continue176		}177		afterBar = false178179		if strings.HasPrefix(text, "!") {180			inv = true181			typ = termExact182			text = text[1:]183		}184185		if text != "$" && strings.HasSuffix(text, "$") {186			typ = termSuffix187			text = text[:len(text)-1]188		}189190		if strings.HasPrefix(text, "'") {191			// 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, "^") {200			if typ == termSuffix {201				typ = termEqual202			} else {203				typ = termPrefix204			}205			text = text[1:]206		}207208		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,221				caseSensitive: caseSensitive})222			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}243244func (p *Pattern) buildCacheKey() string {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) {251			cacheableTerms = append(cacheableTerms, string(termSet[0].text))252		}253	}254	return strings.Join(cacheableTerms, "\t")255}256257// CacheKey is used to build string to be used as the key of result cache258func (p *Pattern) CacheKey() string {259	return p.cacheKey260}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 {287		for idx := 0; idx < chunk.count; idx++ {288			if match, _, _ := p.MatchItem(&chunk.items[idx], false, slab); match != nil {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) {321	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	}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) {334	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	}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}382383func (p *Pattern) transformInput(item *Item) []Token {384	if item.transformed != nil {385		return *item.transformed386	}387388	tokens := Tokenize(item.text.ToString(), p.delimiter)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 {396		if res, pos := pfun(caseSensitive, normalize, forward, part.text, pattern, withPos, slab); res.Start >= 0 {397			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}